我有以下课程。
我已经使用 javac 手动编译了这些类,并运行了Driver
类。
后来删除了entity.class
和MyCustomException.class
,并按如下所示运行了该应用程序。
java驱动程序测试
抱怨以下错误是因为缺少MyCustomException
,而不是关于Entity
类。因此,不清楚为什么JRE抱怨MyCustomException
类,而不抱怨Entity
类。
实际上,我已删除了代码throw new MyCustomException();
,但没有遇到关于Entity
类的错误。
Caused by: java.lang.NoClassDefFoundError: com/techdisqus/exception/MyCustomException
请注意,当我将命令参数传递为 test <时, IF 条件将不执行 / p>
为什么会引发异常,导致加载永远不会执行的MyCustomException
,但是除非满足条件,否则JVM不会加载任何其他常规类,例如此处的Entity
类。请检查下面的Driver.java
。
MyCustomException.java
public class MyCustomException extends RuntimeException {
}
Entity.java
public class Entity {
}
Driver.java
public class Driver {
public static void main(String[] args) {
String s = args[0];
if("true".equals(s)){
Entity entity = new Entity(); // This is not loaded, unless s is true
throw new MyCustomException(); // this is loaded even s is NOT true.
}else{
System.out.println("success");
}
}
}
感谢帮助
答案 0 :(得分:9)
(这是有根据的猜测;我绝不是JVM内部专家)
我假设错误发生在verification期间,当时已加载的类经过了一些健全性检查,因此运行时可以稍后进行一些假设。
检查之一是字节码指令的类型检查。具体是athrow
:
如果操作数堆栈的顶部与Throwable相匹配,则一条throw指令为safe类型。
因此,此时,类加载器必须加载MyCustomException
以检查其是否扩展了Throwable
答案 1 :(得分:-3)