Friday, March 9, 2012

Difference between ClassNotFoundException and NoClassDefFoundError in Java

Difference between ClassNotFoundException and NoClassDefFoundError in Java

Dear Reader,
Many times you might have encountered the above exceptions/errors while running your application built in
Java platform. I am explaining the difference here:

ClassNotFoundException: 
1) This is an Exception, so can be handled using Exception handling in Java.
2) ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the 
   name of class at runtime and then JVM tries to load it and if that class is not found in classpath it 
   throws ClassNotFoundException. 
   So this is thrown when an application tries to load a class through its string name as below:
        a) Class.forName("oracle.driver.Driver");
        b) ClassLoader.findSystemClass("class name") or ClassLoader.findClass("class name").
        c) ClassLoader.loadClass("class name").
   But no definition for the class with the specified name could be found.
3) Also remember this ClassNotFoundException is a Checked Exception, means when you write your code as 
   mentioned above "Class.forName("oracle.driver.Driver")", you must either write this code in try-catch 
   block or use throws keyword else code will not compile.
   
   Solution of this Exception: Set the classpath well.

NoClassDefFoundError:
1) This is an Error, means thrown by JVM so can't be recovered and program crashed.
2) This is basically a linkage error and comes when you create an object using "new MyClassName()" syntax.
   It means at the compilation time the class was available but at runtime it is not available.
   Or,
   Your application is using a class (assume "AA"), that uses another class (assume "BB") inside either as 
   static variable or in static method or anywhere in class "AA". Now your class "AA" is there in classpath
   but class "BB" got missed out then "NoClassDefFoundError" comes.

Example: Now writing complete code for getting above both exception/errors:
1) ClassNotFoundException: 
------------------------------------
    //ClassNotFound.java
    public class ClassNotFound {
        public static void main(String[] args) throws Exception {
            Class c = Class.forName("modi.driver.MyDriver");     //Sample user defined driver name 
        }
    }

    //The above program will compile well, I have declared throws Exception too.
    //But at run time you will get below exception:
    E:\My Workspace\NoClassDefFoundError\src>java ClassNotFound
    Exception in thread "main" java.lang.ClassNotFoundException: modi.driver.MyDriver
            at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
            at java.lang.Class.forName0(Native Method)
            at java.lang.Class.forName(Class.java:164)
            at ClassNotFound.main(ClassNotFound.java:3)
------------------------------------

2) NoClassDefFoundError:
Steps: 
    a. Write a program
    b. Compile it and run it. It will run well.
    c. Delete a class after compilation done, here inner class is deleted.
    d. Run the program again. You will see error.

------------------------------------
//MainProgram.java   
public class MainProgram {
    static class b {}
    public static void main(String args[]) {
        System.out.println("First attempt new b():");
        try {
            new b(); 
        } 
        catch(Throwable t) {
            t.printStackTrace();
        }
        System.out.println("\nSecond attempt new b():");
        try {
            new b(); 
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
    }
}

//Compiling the Java code
E:\My Workspace\NoClassDefFoundError\src>javac MainProgram.java
//Once program is compiled, we will have below classes in the src directory:
Directory of E:\My Workspace\NoClassDefFoundError\src
03/09/2012  08:58 PM               250 MainProgram$b.class
03/09/2012  08:58 PM               676 MainProgram.class
03/09/2012  08:57 PM               362 MainProgram.java

//Running the Java code
E:\My Workspace\NoClassDefFoundError\src>java MainProgram
First attempt new b():

Second attempt new b():

//Deleting the inner class "MainProgram$b.class"
E:\My Workspace\NoClassDefFoundError\src>del MainProgram$b.class

//Now directory contains below files:
E:\My Workspace\NoClassDefFoundError\src>dir
Directory of E:\My Workspace\NoClassDefFoundError\src
03/09/2012  08:58 PM               676 MainProgram.class
03/09/2012  08:57 PM               362 MainProgram.java
--------Removed "MainProgram$b.class"----------

//Running the Java code again
E:\My Workspace\NoClassDefFoundError\src>java MainProgram
First attempt new b():
java.lang.NoClassDefFoundError: MainProgram$b
        at MainProgram.main(MainProgram.java:6)

Second attempt new b():
java.lang.NoClassDefFoundError: MainProgram$b
        at MainProgram.main(MainProgram.java:13)
E:\My Workspace\NoClassDefFoundError\src>
------------------------------------

That's it. Dear reader, if still there is a confusion, please drop a question, I will reply.

5 comments:

  1. I agree both of them appear same but underlying cause is different. see this link which clearly differentiate between NoClassDefFoundError and ClassNotFoundException

    ReplyDelete
  2. Best Explanation I have ever read.Keep Rocking !!

    ReplyDelete
  3. Great help mate...

    -- Anish Sneh
    http://www.anishsneh.com

    ReplyDelete
  4. when we r adding external jar file and got exception like this so how can we fix this issue..plz help me.

    ReplyDelete