Difference between ClassNotFoundException vs NoClassDefFoundError in Java
**ClassNotFoundException **
ClassNotFoundExcpetion comes when we are trying to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in the classpath for example when you try to load Oracle or MySql driver class and their jar file is not available.this exception occurs when you try to run an application without updating the classpath with required JAR files.
try
{
Class.forName("com.mysql.jdbc.driver");
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
If we run the above program without updating the classpath with required JAR files, you will get the following exception
java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
NoClassDefFoundError
In case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Runtime System tries to load the definition of a class, and that class definition is not available at runtime.
class Sample
{
// some code
}
public class Demo
{
public static void main(String[] args)
{
Sample s = new Sample();
}
}
When we compile the above program, two .class files will be generated. One is Sample.class and another one is Demo.class. If we remove the Sample.class file and run the Demo.class file, JVM will throw NoClassDefFoundError like.
Example
Exception in thread "main" java.lang.NoClassDefFoundError: Sample
at Demo.main(MainClass.java:10)