關於NoClassDefFoundError和ClassNotFoundException異常


java.lang.NoClassDefFoundError 和 java.lang.ClassNotFoundException 都是 Java 語言定義的標准異常。從異常類的名稱看似乎都跟類的定義找不到有關,但是還是有些差異。我們先來看一下 java 規范中對這兩個異常的說明:

java.lang.NoClassDefFoundError:

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 the new 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.

出現這個異常,並不是說這個.class類文件不存在,而是類加載器試圖加載類的定義時卻找不到這個類的定義,實際上.class文件是存在的。

You are getting a java.lang.NoClassDefFoundError which does NOT mean that your class is missing (in that case you'd get a java.lang.ClassNotFoundException). The ClassLoader ran into an error while reading the class definition when trying to read the class.

 

java.lang.ClassNotFoundException:

Thrown when an application tries to load in a class through its string name using:
1. The forName method in class Class.
2. The findSystemClass method in class ClassLoader .
3. The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

從規范說明看, java.lang.ClassNotFoundException 異常拋出的根本原因是類文件找不到,缺少了 .class 文件,比如少引了某個 jar,解決方法通常需要檢查一下 classpath 下能不能找到包含缺失 .class 文件的 jar。

 

但是,很多人在碰到 java.lang.NoClassDefFoundError 異常時也會下意識的去檢查是不是缺少了 .class 文件,比如 SO 上的這位提問者(java.lang.NoClassDefFoundError: Could not initialize class XXX)-- “明明 classpath 下有那個 jar 為什么還報這個異常“。而實際上,這個異常的來源根本不是因為缺少 .class 文件。而碰到這個異常的解決辦法,一般需要檢查這個類定義中的初始化部分(如類屬性定義、static 塊等)的代碼是否有拋異常的可能。

如果是 static 塊,可以考慮在其中將異常捕獲並打印堆棧等,或者直接在對類進行初始化調用(如 new Foobar())時作 try  catch。

static{
  try{ 
    ... your init code here
  }catch(Throwable t){
    LOG.error("Failure during static initialization", t);
  }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM