Differences between NoClassDefFoundError and ClassNotFoundException?
NoClassDefFoundError extends LinkageError which in turns extends Error.
Javadoc for Error class states:
An
Error
is a subclass ofThrowable
that indicates serious problems that a reasonable application should not try to catch.
Class loading methods like Class.forName()
only declares ClassNotFoundException
in throws clause. Which, in addition to above description of Error
means that we should not be usually catching the NoClassDefFoundError
when loading classes with Class.forName()
etc.
My question is what are the conditions in开发者_StackOverflow中文版 which NoClassDefFoundError
is thrown instead of ClassNotFoundException
?
ClassNotFoundException
is more likely to be thrown (to your code) in situations where you're manually loading classes - precisely for things like Class.forName()
. These names may come from user input, for example.
NoClassDefFoundError
will occur when a class file itself refers to a class that then can't be found. The class was present at some time, but now isn't - this isn't just a bug in the code that's trying to do reflection, it's a deployment mistake of not making all the required classes available. As far as I can tell a NoClassDefFoundError
will usually or possibly always wrap a ClassNotFoundException
- but the point is that this isn't something your code is meant to guard against, as it indicates an environment which is probably too broken to recover from.
At least, that's my understanding :)
NoClassDefFoundError occures at runtime because compiler not able to find .class file.
精彩评论