ClassNotFoundException
ClassNotFoundException一個異常,該異常為已檢查異常(Checked Exception),可以在編譯期檢查到,需要用戶手工處理。
在Java API中這樣描述:
Thrown when an application tries to load in a class through its string name using:
- The
forNamemethod in classClass.- The
findSystemClassmethod in classClassLoader.- The
loadClassmethod in classClassLoader.but no definition for the class with the specified name could be found.
大致的意思是,當應用調(diào)用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的類,而我們由通過方法反射加載這個類的時候,系統(tǒng)拋出ClassNotFoundException異常。
NoClassDefFoundError
NoClassDefFoundError是一個錯誤,無法在編譯階段檢查到 。
在Java API中這樣描述:
Thrown if the Java Virtual Machine or a
ClassLoaderinstance 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 thenewexpression) 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.
大致意思未,執(zhí)行過程中,JVM或ClassLoader嘗試加載一個類的時候(調(diào)用類的方法或者創(chuàng)建類的對象),找不到某個在編譯器存在且成功編譯的類,此時會拋出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文件編譯后會產(chǎn)生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類的定義。