Sunday, March 15, 2015

Java Difference between NoClassDefFoundError VS ClassNotFoundException in Java

** Difference between NoClassDefFoundError VS ClassNotFoundException in Java **

Both exception due to missing classes in classpath.

First we will see : NoClassDefFoundError 

Class Car{

}

Class Demo
{
  public static void main(String[] args){
   Car car = new Car();
 }

}

e:\Binod> javac Demo.java
It will create Demo.class and Car.class
Now you go and delete Car.class
Now
e:\Binod>java Demo
You will get below exception:
Exception in thread "main" java.lang.NoClassDefFoundError: Car
        at Demo2.main(Demo.java:9)
Caused by: java.lang.ClassNotFoundException: Car
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)


*******  Now we will see ClassNotFoundException ********

ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit

handling for it while NoClassDefFoundError is an Error derived from LinkageError.

public class Demo {
  public static void main(String[] args) {
try {
Class check = Class.forName("Car");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Make sure Car.class should not be there in classpath.
e:\Binod> javac Demo.java
It will create Demo.class only
e:\Binod>java Demo
This time, you will get below exception:

java.lang.ClassNotFoundException: Car
        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)

NOTE:
ClassNotFoundException comes in java if we try to load a class at run-time using with
Class.forName() or
ClassLoader.loadClass() or
ClassLoader.findSystemClass() method
and requested class is not available in Java.