ClassNotFoundException
ClassNotFoundException
一個(gè)異常燎孟,該異常為已檢查異常(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.
大致的意思是,當(dāng)應(yīng)用調(diào)用Class.forName()
剂陡、ClassLoader
中的findSystemClass
,loadClass
方法時(shí)狐胎,對(duì)應(yīng)名稱的類找不到時(shí)鸭栖,會(huì)拋出此異常。
例如:
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)
*/
當(dāng)類路徑中沒有名為com.mysql.jdbc.Driver
的類握巢,而我們由通過方法反射加載這個(gè)類的時(shí)候晕鹊,系統(tǒng)拋出ClassNotFoundException
異常。
NoClassDefFoundError
NoClassDefFoundError
是一個(gè)錯(cuò)誤暴浦,無法在編譯階段檢查到 溅话。
在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.
大致意思未,執(zhí)行過程中歌焦,JVM或ClassLoader
嘗試加載一個(gè)類的時(shí)候(調(diào)用類的方法或者創(chuàng)建類的對(duì)象)飞几,找不到某個(gè)在編譯器存在且成功編譯的類,此時(shí)會(huì)拋出NoClassDefFoundError
錯(cuò)誤同规。
例如:
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文件編譯后會(huì)產(chǎn)生NoClassDefFoundErrorDemo.class
和A.class
兩個(gè)類文件循狰,當(dāng)我們刪除A.class
文件,并且運(yùn)行NoClassDefFoundErrorDemo
類時(shí):
/*
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
*/
會(huì)拋出NoClassDefFoundError
錯(cuò)誤券勺,提示找不到liheng.exception.A
類的定義绪钥。