What is NoClassDefFoundException in Java

Points To Remember

  1. NoClassDefFoundException is an Exception that occurs when a class is not found at runtime but was available at compile time.
  2. This exception is different from ClassNotFoundException. See the differences here.

Example : Creating a NoClassDefFoundException

Suppose we have two classes A and Test. We just make an object of class A in Test class.
A.java
class A{
   public A(){
      System.out.println("This is class A");
   }
}
Test.java
class Test{
  public static void main(String args[]){
    System.out.println("This is Test Class");
    A obj = new A();
  }
}
The output of the program will be as follows
This is Test Class
This is class A
Now Suppose if you delete the class A.class from the current path and run the Test class you will get the following output
This is Test Class
Exception in thread "main" java.lang.NoClassDefFoundError: A
at Test.main(Test.java:12)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 1 more

This is the how NoClassDefFoundException is caused. So if you get this exception in your application, it means that some of the classes that were there at compile time are missing at runtime.

No comments:

Powered by Blogger.