NoClassDefFoundError VS ClassNotFoundException

341 阅读1分钟

背景

我们在开发过程中经常碰见NoClassDefFoundError和ClassNotFoundException这两种异常,但是我们很难真正的分别这两个类,那么我们从以下几方面对比这两个异常:

  • 定义
  • 出发的原因
  • 如何解决

定义

NoClassDefFoundError

继承的是Error,下面是jdk的注释:

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class  and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

如果Java虚拟机或ClassLoader实例加载类的定义抛出,则找不到该类的定义。 类在编译时存在,但是运行时无法再找到该类。

ClassNotFoundException

继承了Exception

Thrown when an application tries to load in a class through its string name using:
* The forName method in class Class.
* The findSystemClass method in class ClassLoader .
* The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

当应用程序使用其字符串名称动态加载类时抛出

  • Class.forName(String);
  • ClassLoader.findSystemClass(String);
  • ClassLoader.loadClass(String, boolean);

什么时候触发

NoClassDefFoundError:类编译时候存在,运行时候不存在;比如说:在运营时候将.class文件删除 ClassNotFoundException:是在通过以下三个方法加载时候

  • Class.forName(String);
  • ClassLoader.findSystemClass(String);
  • ClassLoader.loadClass(String, boolean);

如何解决

ClassNotFoundException是Exception可以程序捕获异常来处理 ClassNotFoundException是Error,应用程式无法处理