Let's first see some similarities which are main reason of confusion between these two errors:
- Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.
- Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
Now let's see the difference between the two:
- 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. Most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option. On the other hand in NoClassDefFoundError case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.
- ClassNotFoundException is a checked 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.
- If you are using ClassLoader 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.
- 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.
Copyright © 2013 - ScrutinyByKHimaanshu
No comments:
Post a Comment