Differences between NoClassDefFoundError and ClassNotFoundException?

NoClassDefFoundError extends LinkageError, which in turn extends Error.

Javadoc for error class states:

An Error is a subclass of Throwable which indicates serious problems that a reasonable use should not be attempted to catch.

Class loading methods, such as Class.forName() , only declare ClassNotFoundException in throws. Which, in addition to the above description of Error , means that we should not usually catch NoClassDefFoundError when loading classes using Class.forName() , etc.

My question is: what are the conditions under which a NoClassDefFoundError is NoClassDefFoundError instead of a ClassNotFoundException ?

+6
java classloader
source share
2 answers

ClassNotFoundException will most likely be thrown (in your code) in situations where you manually load the classes - just for things like Class.forName() . These names may come, for example, from user input.

NoClassDefFoundError will occur when the class file itself refers to a class, which then cannot be found. The class was present at some point, but now itโ€™s not so - itโ€™s not just an error in the code that it is trying to reflect, it is a deployment error so as not to make all the necessary classes available. As far as I can tell, a NoClassDefFoundError usually or perhaps always NoClassDefFoundError ClassNotFoundException , but the fact is that this is not what your code is designed to protect against, as it points to an environment that is probably too broken to recover from.

At least that's my understanding :)

+12
source share

NoClassDefFoundError occurs at runtime because the compiler cannot find the .class file.

0
source share

All Articles