ClassNotFoundException and NoClassDefFoundError

Points To Remember
  • ClassNotFoundException is an Exception.
  • NoClassDefFoundError is an Error.
ClassNotFoundException
This is a type of error when we are trying to access a class but that class is not available at the classpath or at the path specified by us. This type of error is thrown when an application tries to load in a class through its string name using:
  1. The forName method in class Class.
  2. The findSystemClass method in class ClassLoader.
  3. The loadClass method in class ClassLoader.
Example : When ClassNotFoundException occurs
class A{}

class Test{

 public static void main(String args[]){
  try{
    System.out.println("classA = "+Class.forName("A").getClass());
    System.out.println("classB = "+Class.forName("B").getClass());
  }catch(ClassNotFoundException e){
    System.out.println("ClassNotFoundException");
  }
 }

}
classA = class java.lang.Class
ClassNotFoundException
Since the class A is found class.forName() returns the instance of class but since class Test did not find class B, it threw ClassNotFoundException.

NoClassDefFoundError
This is a type of error which occurs at runtime. It occurs when a class uses some other class which was available at the compile time but is not available at the run time.
Example : When ClassNotFoundException occurs

Class : A.java

class A{
 public A(){
   System.out.println("Class A");
 }
}

Class : Test.java

class Test{

 public static void main(String args[]){
   System.out.println("Class Test");
   A object = new A();
 }

}
The above code complies successfully and gives the following output.
Class Test
Class A
Now if we intentionally delete class A, then we will start getting the following output at run time.
Class Test
Exception in thread "main" java.lang.NoClassDefFoundError: A
 at Test.main(Test.java:5)
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

No comments:

Powered by Blogger.