Monday, 29 July 2013

Difference Between NoClassDefFoundError and ClassNotFoundException


According to Java doc

ClassNotFoundException is thrown when an application tries to load in a class through its string name using:

    The forName method in class Class.
    The findSystemClass method in class ClassLoader .
    The loadClass method in class ClassLoader.

     http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassNotFoundException.html
  
Example:

package hardik4u;

public class ExpClassNotFound {

    public static void main(String[] args) {
       
        //i have tried to load class which is not exists using Class.forName
       
        try {
            Class.forName("hardik4u.TestDate");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           
        }
      
  }
}


while

NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

    http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/NoClassDefFoundError.html
  
Example:

package hardik4u;

public class ExpClassDefNotFound {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // Create one Class TestData in the same package
        // compile TestData and add below line in ExpClassDefNotFound class and compile it.
        // remove TestData.class and run
        // Java ExpClassDefNotFound
        // it will give ClassDefNot Found Error
       
       
        TestData testData =new TestData();

    }

}

No comments:

Post a Comment