Search code examples
javaclassloaderstack-tracenoclassdeffounderrorclassnotfoundexception

Does NoClassDefFoundError have always ClassNotFoundException in caused by?


Can I assume that every NoClassDefFoundError thrown from JDK class loading mechanism will always have ClassNotFoundException as a cause in stacktrace?

Also, where actually NoClassDefFoundError is thrown and its cause is initialized to be ClassNotFoundException? I cannot find Java code responsible for that logic.

This is how usually stacktraces look to me:

Exception in thread "main" java.lang.NoClassDefFoundError: package/Missing
    at package.Missing(Missing.java:110)
Caused by: java.lang.ClassNotFoundException: package.Missing
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

Solution

  • Can I assume that every NoClassDefFoundError thrown from JDK class loading mechanism will always have ClassNotFoundException as a cause in stacktrace?

    That's a reasonable assumption. According to the Java Virtual Machine Specification:

    If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.

    I believe the above answers your second question as well.