ClassNotFoundException
ClassNotFoundException
一个异常,该异常为已检查异常(Checked Exception),可以在编译期检查到,需要用户手工处理。
在Java API中这样描述:
Thrown when an application tries to load in a class through its string name using:
- The
forName
method in classClass
.- The
findSystemClass
method in classClassLoader
.- The
loadClass
method in classClassLoader
.but no definition for the class with the specified name could be found.
大致的意思是,当应用调用Class.forName()
、ClassLoader
中的findSystemClass
,loadClass
方法时,对应名称的类找不到时,会抛出此异常。
例如:
public class ClassNotFoundExceptionDemo {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c = Class.forName("com.mysql.jdbc.Driver");
}
}
/*
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at liheng.exception.ClassNotFoundExceptionDemo.main(ClassNotFoundExceptionDemo.java:5)
*/
当类路径中没有名为com.mysql.jdbc.Driver
的类,而我们由通过方法反射加载这个类的时候,系统抛出ClassNotFoundException
异常。
NoClassDefFoundError
NoClassDefFoundError
是一个错误,无法在编译阶段检查到 。
在Java API中这样描述:
Thrown if the Java Virtual Machine or a
ClassLoader
instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using thenew
expression) and no definition of the class could be found.The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
大致意思未,执行过程中,JVM或ClassLoader
尝试加载一个类的时候(调用类的方法或者创建类的对象),找不到某个在编译器存在且成功编译的类,此时会抛出NoClassDefFoundError
错误。
例如:
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
A a = new A();
a.print();
}
}
class A {
public void print() {
System.out.println("A print");
}
}
将.java文件编译后会产生NoClassDefFoundErrorDemo.class
和A.class
两个类文件,当我们删除A.class
文件,并且运行NoClassDefFoundErrorDemo
类时:
/*
Exception in thread "main" java.lang.NoClassDefFoundError: liheng/exception/A
at liheng.exception.NoClassDefFoundErrorDemo.main(NoClassDefFoundErrorDemo.java:5)
Caused by: java.lang.ClassNotFoundException: liheng.exception.A
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
*/
会抛出NoClassDefFoundError
错误,提示找不到liheng.exception.A
类的定义。