Tuesday, November 2, 2010

Difference between NoClassDefFoundError & ClassNotFoundException

java.lang.NoClassDefFoundError is thrown when we try create an object of a class and the runtime environment is not able to load the given class. This happens when we create the object using the new operator. The searched class though existed when the calling class was compiled but at run time the classloader wasn't able to find the binary code.

java.lang.ClassNotFoundException is thrown when a class is being loaded by the class loader. The class is presumed to be present in any the jar files located in the classpath,or lib. This exception is thrown when the forName method in the class or the findSystemClass/loadClass methods in the ClassLoader is being used.

The following program demonstrates the two , the first method createNew throws the NoClassDefFoundError and the second method loadClass throws ClassNotFoundException.


public class TestException {
public static void main(String[] args) {
createNew();
loadClass();
}
private static void createNew(){
FirstClass fc= new FirstClass();
}
private static void loadClass(){
try {
Class cla11 = Class.forName("collectionsTest.FirstClass");
FirstClass firstClass = (FirstClass)cla11.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


A very good post on this is provided here

No comments:

Post a Comment