What is the difference between ClassNotFoundException and NoClassDefFoundError? (or) ClassNotFoundException vs NoClassDefFoundError

Both ClassNotFoundException and NoClassDefFound will occur when some class is not available at run time. But they occur in different scenarios.

 

ClassNotFoundException

This method is thrown when an application tries to load a class that mentioned in one the methods Class.forName or loadClass or findSystemClass and the class that mentioned in one these methods not present at run time. This exception occurs when you implemented a program using some libraries but the class path is not update with those libraries at run time.

Example Code:

public class ClassNotFoundDemo {
public static void main(String[] args) {
try {
Class loadedClass = Class.forName("ClassWhichIsNotPresent");
System.out.println("Class " + loadedClass + " found successfully!");
}
catch (ClassNotFoundException ex) {
System.err.println("A ClassNotFoundException was caught: " + ex.getMessage());
ex.printStackTrace();
}
}
}

Output:

A ClassNotFoundException was caught: ClassWhichIsNotPresent
java.lang.ClassNotFoundException: ClassWhichIsNotPresent
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at HelloWorld.main(ClassNotFoundDemo.java:6)

NoClassDefFoundError

This error will occur when JVM tries to load a class definition that is no longer available. The class definition was present at compile time but not available at run time.

Example code:

Create a class that contains main method similar to below:

public class NoClassDefFoundDemo 
{ 
public static void main(String[] args) {
MyClass cls = new MyClass();
cls.myMethod();
}
}

Create another class that we used in the above class:

class MyClass {
public void myMethod()
{
System.out.println("myMethod called");
}
}

 

Compile both the source classes and remove the .class file i.e., MyClass.class that is generated so that at run time the class file will not available for the calling method. Now run the class file that contains the method.

Output:

 

Differences

ClassNotFoundEception -

  •  This is an exception of type java.lang.Exception
  • Occurs when JVM tries to load a class which not available because of not updating the class path
  • Will be thrown by  Class.forName() or loadClass() or findSystemClass() methods.

NoClassDefFoundError -

  • This is an error of type java.lang.Error
  • Occurs when Java run time tries to load a class definition that is present at compile time but not present at run time.
  • This will be thrown by Java Run time System not need of calling any methods.

 

Leave a Reply

Your email address will not be published. Required fields are marked *