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

前端 未结 15 2344
忘了有多久
忘了有多久 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:11

    With the names itself we can easily identify one from Exception and other one is from Error.

    Exception: Exceptions occurs during the execution of program. A programmer can handle these exception by try catch block. We have two types of exceptions. Checked exception which throws at compile time. Runtime Exceptions which are thrown at run time, these exception usually happen because of bad programming.

    Error: These are not exceptions at all, it is beyond the scope of programmer. These errors are usually thrown by JVM.


    image source

    Difference:

    ClassNotFoundException:

    • Class loader fails to verify a class byte code we mention in Link phase of class loading subsystem we get ClassNotFoundException.
    • ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it
    • 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() and ClassLoader.findSystemClass().

    NoClassDefFoundError:

    • Class loader fails to resolving references of a class in Link phase of class loading subsystem we get NoClassDefFoundError.
    • NoClassDefFoundError is an Error derived from LinkageError class, which is used to indicate error cases, where a class has a dependency on some other class and that class has incompatibly changed after the compilation.
    • NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.

    Similarities:

    • Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
    • Both ClassNotFoundException and NoClassDefFoundError are related to Java classpath.

提交回复
热议问题