ClassNotFoundException vs NoClassDefFoundError

ClassNotFoundException NoClassDefFoundError
Exception or Error? It is of type java.lang.Exception.It is a Checked Exception. It is of type java.lang.Error.
When it occurs?Explicit loading or Implicit loading? It occurs when an application tries to load a class at run time which is not found in the classpath.

Explicit loading:It is thrown when the code is directly trying to load a class, passing the String argument representing a Fully Qualified Name of the class.
e.g. Class.forName(String), or ClassLoader.loadClass(String).

It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.

Implicit loading:It is thrown when the JVM is asked to load a class indirectly.
e.g. when class A is using class B and class B is not on classpath, NoClassDefFoundError will be thrown.

Situations in which these are thrown? It occurs 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. When JVM 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 (bad format of the class, the version number of a class not matching, etc.).
Class can’t be loaded on the following reasons:
failure to load the dependent class;
the dependent class has a bad format;
the version number of the class is incorrect;
the class been loaded already in a different classloader;exception from static block
etc.
Thrown by? It is thrown by the application itself. It is thrown by the JVM.
Irrecoverable or Recoverable? Irrecoverable:NoClassDefFoundError refers irrecoverable situation that are not being handled by try/catch/finally block.
Recoverable:ClassNotFoundException is checked exception, which requires handling using try/catch/finally block.

Example

ClassNotFoundException

package com.test;

public class TestClass {

public static void main(String[] args) throws ClassNotFoundException {
Class.forName(“com.test.TestClass1”);
}

}

Output

Screen Shot 2017-03-19 at 10.04.54 PM

NoClassDefFoundError

Example1: Exception in static block

package com.test;

public class TestClass {

static{
int i=10/0;//Arithmetic Exception
}

public static void main(String[] args) throws ClassNotFoundException {
TestClass testclass = new TestClass();
}

}

Screen Shot 2017-03-19 at 10.10.09 PM

 

 

 

Example2:

On deleting the .class file after successful compilation. It will throw NoClassDefFoundError.

package com.test;

public class TestClass {

public static void main(String[] args) throws ClassNotFoundException {

TestClass testclass = new TestClass();

}

}

Screen Shot 2017-03-19 at 10.15.52 PM.png

Leave a Reply

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