Pages

Wednesday, February 16, 2011

ClassNotFoundException or NoClassDefFoundError.. what the hell is going on...

many a times we face "ClassNotFoundException" or  "NoClassDefFoundError"  and then we wonder what the hell is going on... not able to figure out what went wrong... some times we even see that even though class file or jar was exist in classpath, classloader unable to find it...
first try to understand that  "ClassNotFoundException" is thrown when specified class was not found in classpath by classloader, simply its a missing class in classpath or in a jar.
"NoClassDefFoundError" is also similar but with bit difference that it is a runtime error that is thrown by JVM when classloader did not find class definition while loading class caused by  "ClassNotFoundException",  it means that class was present at compile time but does not present at run time". normally both (error and exception) will print the causing class name that was not found by the classloader.

but if you come to notice that even though if class is present in classpath or in a jar and still classloader gives same error then try to look for dependent class imported inside the class that was thrown as "ClassNotFoundException"
Also check is that class has some static block/class variable defined from other package or jar, then make sure even those class/jars are present in classpath


in case of web applications or case where you use framworks like struts/spring or hibernate exceptions are wrapped and you may not come to know actual error that was causing the problem... some such scenarios could be

1. in web applications classloader has child and parent classloaders where classes loaded by parent are accessable to child classloaders but not child to parent. so in such case need to know which classloader is loading the class. for e.g. if you have some class (or class in jar)from shared lib of application referring to web-inf/lib or folder...

2. version compatibility. sometimes it happens that your application jdk is of lower version and jars created in higher version will create unsupported classversion error.. but thrown error could be "ClassNotFoundException"

3. recheck the fully qualified class name that may have typo error, e.g. class.forname or applicationcontext.xml in case of spring where beans are defined.