Tuesday, June 09, 2009

ClassNotFoundException vs. NoClassDefFoundError

Many a times we will come across these exceptions, though they look similar there is a clear difference between these two classes.

package com.test;

/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class A {

public void print() {
System.out.println("I am A");
}

}


package com.test;

/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class B {

public static void main(String[] args) {
try {
Class clazz = Class.forName("com.test.A");
A a = (A) clazz.newInstance();
a.print();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

}


package com.test;

/**
* @author Vijayan Srinivasan
* @since Sep 22, 2010 9:16:46 PM
*/
public class C {

private A a = new A();

public static void main(String[] args) {
new C().a.print();
}

}

First compile all these classes. Once compilation is complete, then run the class B and C
You will get the following output.

C:\Test\bin>java com.test.C
I am A

C:\Test\bin>java com.test.B
I am A

Now delete class A and re-run the classes B & C

C:\Test\bin>java com.test.C
Exception in thread "main" java.lang.NoClassDefFoundError: com/test/A
at com.test.C.(C.java:12)
at com.test.C.main(C.java:15)
Caused by: java.lang.ClassNotFoundException: com.test.A
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 2 more

C:\Test\bin>java com.test.B
java.lang.ClassNotFoundException: com.test.A
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.test.B.main(B.java:15)

No comments: