ทั้ง ClassNotFoundException และ NoClassDefFoundError เป็น error เมื่อ JVM หรือ ClassLoader ไม่สามารถหาคลาสที่เหมาะสมขณะโหลดที่ run-time ClassNotFoundException เป็น checked exception และ NoClassDefFoundError เป็น Error ซึ่งอยู่ใน unchecked
มี ClassLoader หลายประเภท โหลดคลาสจากแหล่งต่างกัน บางครั้งอาจทำให้ library JAR files หายไป หรือ class-path ผิด ทำให้ loader ไม่สามารถโหลดคลาสที่ run-time ได้
ClassNotFoundException
ClassNotFoundException เกิดขึ้นเมื่อเราพยายามโหลดคลาสที่ run-time โดยใช้ Reflection และถ้า class files นั้นหายไป แอปพลิเคชันหรือโปรแกรมจะโยน ClassNotFoundException ไม่มีอะไรให้ตรวจสอบที่ compile-time เพราะมันโหลดคลาสที่ run-time
ตัวอย่าง
public class ClassNotFoundExceptionTest {
public static void main(String[] args) {
try {
Class.forName("Test");
} catch (ClassNotFoundException cnfe) {
System.err.println("You are trying to search for a class is not existing. "+cnfe);
}
}
}
ผลลัพธ์
You are trying to search for a class is not existing. java.lang.ClassNotFoundException: Test
NoClassDefFoundError
NoClassDefFoundError โยนเมื่อคลาสถูกคอมไพล์กับคลาสเฉพาะจาก classpath แต่ถ้าคลาสเดียวกันไม่พร้อมใช้งานระหว่าง run-time ไฟล์ JAR หายไปเป็นเหตุผลพื้นฐานที่สุดของ NoClassDefFoundError ตาม Java API docs "The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found."
ตัวอย่าง
class Test1 {
public void show() {
System.out.println("show() method called");
}
}
public class Test2 {
public static void main(String[] args) {
Test1 t = new Test1();
t.show();
}
}
เมื่อคอมไพล์ทั้งสองคลาส จะได้ไฟล์ class 2 ไฟล์ คือ Test1.class และ Test2.class ขณะรัน Test2 class แค่ลบ Test1.class file ออก แล้วจะได้ NoClassDefFoundError ด้านล่าง
ผลลัพธ์
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
at Test2.main(Test2.java:9)