Video in progress
What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is a checked exception thrown when code tries to load a class dynamically by name (Class.forName) and can't find it. NoClassDefFoundError is an Error thrown when a class that existed at compile time is missing at runtime, or when its initialization failed earlier.
📖 Answer
ClassNotFoundException usually shows up where you expect it:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
// the driver jar is not on the classpath
}
NoClassDefFoundError shows up unexpectedly: the code says new ReportBuilder(), javac saw it, but at startup the class is missing. Typical causes:
- the dependency stayed in the
providedortestscope and didn't make it into the jar; - two library versions collided and the needed class is missing from the older one;
- the class's static block threw an exception earlier. On the first attempt
ExceptionInInitializerError, on every later attemptNoClassDefFoundError: Could not initialize class ....
The third case is the most misleading: the class is sitting in the jar, but the error says "not found". Search up the log: the first ExceptionInInitializerError shows the real cause.
To check: mvn dependency:tree or ./gradlew dependencies, and with -verbose:class you can see what was loaded from which jar.
Sign up to mark studied questions and save your progress.