What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

前端 未结 15 2388
忘了有多久
忘了有多久 2020-11-21 05:27

What is the difference between NoClassDefFoundError and ClassNotFoundException?

What causes them to be thrown? How can they be resolved?

15条回答
  •  醉梦人生
    2020-11-21 06:04

    I remind myself the following again and again when I need to refresh

    ClassNotFoundException

    Class Hierarchy

    ClassNotFoundException extends ReflectiveOperationException extends Exception extends Throwable
    

    While debugging

    1. Required jar, class is missing from the classpath.
    2. Verify all the required jars are in classpath of jvm.

    NoClassDefFoundError

    Class Hierarchy

    NoClassDefFoundError extends LinkageError  extends Error extends Throwable
    

    While debugging

    1. Problem with loading a class dynamically, which was compiled properly
    2. Problem with static blocks, constructors, init() methods of dependent class and the actual error is wrapped by multiple layers [especially when you use spring, hibernate the actual exception is wrapped and you will get NoClassDefError]
    3. When you face "ClassNotFoundException" under a static block of dependent class
    4. Problem with versions of class. This happens when you have two versions v1, v2 of same class under different jar/packages, which was compiled successfully using v1 and v2 is loaded at the runtime which doesn't has the relevant methods/vars& you will see this exception. [I once resolved this issue by removing the duplicate of log4j related class under multiple jars that appeared in the classpath]

提交回复
热议问题