ClassNotFoundException vs NoClassDefFoundError in Java
As the name suggests NoClassDefFoundError is an error while ClassNotFoundException is an exception. There is a difference between error and exception in Java. While one can recover from an Exception, no attempt should be made to recover from an error.
Reason for ClassNotFoundException
Java supports dynamic loading of classes by the use of Class.forName method. Any class name passed as argument to this method causes the class to be loaded into JVM memory. If the class is not found on the class path then ClassNotFoundException is thrown at runtime.
Fixing this exception is easy. The only thing required to fix ClassNotFoundException is to ensure the class with specified package is present in the class path. When Class.forName is used, the class loader looks for the class in class path. If found, the class is successfully loaded or else ClassNotFoundException is thrown at run time. Apart from Class.forName, Classloader.loadClass and Classloader.finsSystemClass are also used to dynamically load the class into memory, Hence this exception may be raised due to either of these methods.
Another case when we could be getting ClassNotFoundException is when a class is already loaded into memory by one class loader and another class loader also tried to load the class dynamically from same package.
Since the dynamic loading of class is under the developer control to some extent, he may choose to catch this exception and take appropriate action. Some programs may want to ignore the exception and take an alternative approach. Others may want to terminate the execution and ask the user to perform some steps before re-trying.
Reason for NoClassDefFoundError
This error is raised when a class has been successfully resolved at runtime but the same could not be found at runtime. The error comes when say you are trying to create an object with the help of new operator but the class is not present when executing the program. NoClassDefFoundError is raised by JVM and hence no attempt should be made to catch the error
The only way to resolve this error is to look for any class which was there in class path during development but has been removed from class path at run time. When this error is raised, the name of class is also specified which can make the job of finding the missing class easy.