Friday, March 2, 2012

NoClassDefFoundError vs ClassNotFoudException

I hit one tricky NoClassDefFoundError recently and I ended up searching the web quite intensively about my issue. Interestingly, I realized that many people are questioning about the difference between NoClassDefFoundError (NCDFE) and ClassNotFoundExcpetion (CNFE), and they are confused, they are falling into harsh discussions on blogs, they create many artificial Java code snippets to prove they are right and the others are wrong. But in the end I think they are missing the important point about these two exceptional states in Java.

So let me contribute to this discussion today.

To me the most important point is that one of them is Error, the other one is Exception. According to JavaDoc definition, application may not want to recover from Errors as they are usually fatal, but application can try to recover from Exceptions (more specifically, application may consider to catch Exceptions).

Given this if you want to sum up the difference between NCDFE and CNFE in short then I would say that CNFE (the Exception) is fired when there might be a reason to recover from the situation - for example you try to load particular class from classpath but it is not found, so you might want to consider loading a different class instead.
Contrary NCDFE (the Error) is fired when you have no chance to recover, it is too late, that means you directly try to make use of the class that is not available (as JavaDoc says, you either call constructor or make a method call). And this does not say nothing about whether the class is on classpath or not (it can be available but loading fails due to broken static initialization for example).

In my particular case the class was NOT located on the classpath (you can find option -verbose:class useful in such situation). May be you ask, why I did not get the CNFE Exception first instead? Well, that is a good question and one possible option is that such Exception could haven been swallowed silently earlier in the code.

By no means this is a detailed analysis of differences between NCDFE and CNFE but in all the discussions on the web I was simply missing such highlevel point of view. And in some cases it is important to step back and see things from further distance.

Comments welcome.

No comments: