From last few weeks I have been facing a cluster of ClassNotFoundException and NoClassDefFoundError while setting up a new . This new has lots of on various jars and some of the jar even contains the same name of file which makes my problem even more problematic. While working with NoClassDefFoundError and ClassNotFoundException I thought to my experience and I have already shared some on 3 ways to resolve NoClassDefFoundError in java and how to resolve ClassNotFoundException in java. in this article though focus will be on similarity and differences between java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError in Java.
NoClassDefFoundError vs ClassNotFoundExceptionBefore seeing the differences between ClassNotFoundException and NoClassDefFoundError let's see some similarities which are main reason of confusion between these two errors:
1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.
Now let's see the difference between NoClassDefFoundError and ClassNotFoundException:
1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have How classpath works in java. On the other NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason. in classpath but eventually it turns out to be issue related to classpath and may not be using classpath what we think it was using e.g. classpath defined in jar's file will take precedence over CLASSPATH or -cp option, for see
2) ClassNotFoundException is a Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.
3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.
4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.
Please let us know if you are aware of any other difference between NoClassdefFoundError and ClassNotFoundException in Java , I would be happy to those.