Difference between ClassNotFoundException and NoClassDefFoundError Priyanka_JTC | Nov 18 2011 | Comments (0) | Visits (333) Difference betweenClassNotFoundException and NoClassDefFoundError
ClassNotFoundException is a checked Exception, Its thrown when that required class is not present in the location where classloader is looking. This exception can be created using following program-
import java.net.URL; import java.net.URLClassLoader; public class ClassNotFoundExceptionTest { public static void main(String args[]) { try { URLClassLoader loader = new URLClassLoader(new URL[] { new URL( "file://C:/CL/ClassNotFoundException/")}); loader.loadClass("DoesNotExist"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } }
To avoid this error , User should check the following - - Make sure that Class is available in the logical class path of the class loader associated with the class. - Make sure that Class Loader API is used properly .ie whether a wrong class Loader is engaged in Class.forname(). - Make sure that dependent class of the class being loaded is visible to the class loader. NoClassDefFoundError is an error .Its thrown to indicate that ClassLoader instance is trying to load in the definition of a class and no definition of the class is found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. This error can be recreated using following test program – public class NoClassDefFoundErrorTest { public static void main(String[] args) { A a = new A(); } } public class A extends B { } public class B { } //Once you've compiled the above code remove the classfile for B. When //the code is executed, the following error occurs //Exception in thread "main" java.lang.NoClassDefFoundError: B
Possible reasons of the error- - This can happen in the distribution or production of JAR files, where not all the required class files were included. User should check whether a Class is not available on the classpath(not missing in the jar file). This problem can occur also when Class cannot load . The difference between the two is that one is an On the other hand, the
|