Naruto_Uzumaki Naruto_Uzumaki - 9 months ago 64
Java Question

ClassNotFoundException vs NoClassDefFoundError

I have gone through this thread What is the difference between NoClassDefFoundError and ClassNotFoundException?
This is what one of the ans,which has max ups, in thread is :
NoClassDefFoundError :"So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included."

ClassNotFoundException : As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.

I did a small experiment . I created a main class, class A and tried to call other class, class B from it , compiled successfully.

Then i deleted the class B which is being called in class A.
I got the java.lang.ClassNotFoundException but as per the answer in the tread, i should have got NoClassDefFoundError (source was compiled succesfully but at runtime class files were not found)
Could anyone explain what am i missing in the interpretation of the ans in the thread ?

package com.random;

public class A {

public static void main(String[] args) {
B b= new B();



package com.random;

public class B {


Answer Source

Well... ClassNotFoundException occurs when the runtime is trying to find the class named by some String for example Class.forName(java.lang.String) method take a string argument and tries to find the class with this name. In this case the class-name is a sting and can only be checked at runtime. here the exception clearly says... this "class" is not found. So... it can happen for two reasons :

Reason 1. Class-name is not a valid java-class ( example - "java.bang.kiting").

// Example    
Class cdef = Class.forName( "java.bang.kiting" );

Reason 2. Class-name is was a valid class... but somehow it was not packaged with the jar or is not resolved in class-path. So as far as the runtime knows... it can be a wrong class name... similar to case 1.

// Example    
Class cdef =Class.forName( "apache.some.SomeLegitClass" );

Where as NoClassDefFoundError for cases where the actual class reference was used,

// example
import apache.some.SomeLegitClass
SomeLegitClass i = (SomeLegitClass) instanceOfSomeLegitClass;

So basically the everything was correct but somehow the class is not packaged with the jar ( or more generally - is not resolved in the class-path ). In this case we get NoClassDefFoundError.

Here runtime knows that the class is valid since it compiled successfully... but it can not find the "class definition".