ClassNotFoundException and NoClassDefFoundError both indicate class loading failure they occur in different scenarios and have different root causes. ClassNotFoundException occurs when a class is missing at runtime while loading it dynamically through mechanisms like Class.forName. while NoClassDefFoundError appears when the class was available during compilation but cannot be found or loaded at runtime.
What Is ClassNotFoundException?
ClassNotFoundException is a checked exception thrown when a class is requested at runtime but the JVM cannot locate it in the classpath.
- Occurs when a class is loaded dynamically
- Happens during runtime
- Usually caused by missing or incorrect classpath entries
- Thrown by Class.forName(), ClassLoader.loadClass() and reflection-based operations
public class Demo {
public static void main(String[] args) {
try {
Class.forName("com.example.MissingClass");
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
}
}
}
This exception appears when the class com.example.MissingClass is not present in the runtime classpath.
What Is NoClassDefFoundError?
NoClassDefFoundError is an error thrown by the JVM when it tries to load a class that was available during compilation but is missing at runtime.
- Occurs when a class was compiled successfully but cannot be found later
- Happens during class loading by the JVM
- Indicates missing JAR files or removed classes after compilation
- Raised as an error not as an exception
public class Main {
public static void main(String[] args) {
Helper.help();
}
}
class Helper {
static void help() {
System.out.println("Running");
}
}
If the Helper class gets deleted from the classpath after compilation the JVM throws NoClassDefFoundError when executing the program.
Comparison Table: ClassNotFoundException Vs NoClassDefFoundError
| Aspect | ClassNotFoundException | NoClassDefFoundError |
|---|---|---|
| Type | Checked exception | Error |
| Thrown By | Application code | JVM |
| When It Occurs | Runtime while loading a class dynamically | Runtime when a previously available class is now missing |
| Typical Cause | Wrong or missing classpath for dynamic loading | Missing JAR or class removed after compilation |
| Common Scenarios | JDBC drivers reflection frameworks | Deployment issues, incorrect builds missing dependencies |