views:

56

answers:

1

NoClassDefFoundError extends LinkageError which in turns extends Error.

Javadoc for Error class states:

An Error is a subclass of Throwable 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 which NoClassDefFoundError is thrown instead of ClassNotFoundException?

+4  A: 

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 :)

Jon Skeet
@Downvoter: Care to say why?
Jon Skeet