What is the difference between NoClassDefFoundError
and ClassNotFoundException
?
What causes them to be thrown? How can they be resolved?
With the names itself we can easily identify one from
Exception
and other one is fromError
.
Exception: Exceptions occurs during the execution of program. A programmer can handle these exception by try catch block. We have two types of exceptions. Checked exception which throws at compile time. Runtime Exceptions which are thrown at run time, these exception usually happen because of bad programming.
Error: These are not exceptions at all, it is beyond the scope of programmer. These errors are usually thrown by JVM.
image source
Difference:
ClassNotFoundException:
ClassNotFoundException
.ClassNotFoundException
is a checked Exception derived directly from java.lang.Exception
class and you need to provide explicit handling for it ClassNotFoundException
comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass(), Class.forName() and ClassLoader.findSystemClass().NoClassDefFoundError:
NoClassDefFoundError
. NoClassDefFoundError
is an Error derived from LinkageError
class, which is used to indicate error cases, where a class has a dependency on some other class and that class has incompatibly changed after the compilation. NoClassDefFoundError
is a result of implicit loading of class because of a method call from that class or any variable access.Similarities:
NoClassDefFoundError
and ClassNotFoundException
are related to unavailability of a class at run-time. ClassNotFoundException
and NoClassDefFoundError
are related to Java classpath.