Tuesday, 13 September 2016

Difference between noClassDefFoundError and ClassNotFoundException

Before discussing the difference lets talk about their similarities.
1.Both occur because of  the unavailability of class at runtime at classpath.

Differences -
1.noClassDefnFoundError is error and cant be handled while ClassNotFoundExceptionis exception and can be handled.

2.The exception occurs when we try to load class at runtime using
Class.forName()  or
ClassLoader.loadClass()

In short,
The difference is the root cause of the problem->

ClassNotFoundExcpetion occurs when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath  
Eg.
Your are trying to load jar file and that jar file is not found in classPath.

 noClassDefFoundError occurs when requested class was present at compile time but not available at runtime.
 This happens because of exception during class Initialization.

How to test?
Step1- Create below files -
1. Test.java -->
 public class Test {}
2.Test1,java-->
public class Test1{
Test test = new Test();
}

Step 2.Now compile Test1.java
javac Test1.java
 2 class files will be generated Test.class and Test1.class

Step3. Now delete Test.class file and run Test1.java

noClassDefnFoundError occurs.
 

No comments:

Post a Comment