为什么抛出异常会尝试加载扩展异常的 class(尽管它未执行)而不是常规的 class
Why throwing an exception tries to loads the class which extends Exception (though it is not executed) but not a regular class
我有以下 classes.
我使用 javac 和 运行 Driver
class.[=30= 手动编译了 classes ]
稍后 删除了 entity.class
和 MyCustomException.class
以及 运行 应用程序,如下所示。
java Driver test
以下错误是关于缺少 MyCustomException
而不是关于 Entity
class 的。所以,不清楚为什么 JRE 抱怨 MyCustomException
class 而不是 Entity
class。
确实我已经删除了代码 throw new MyCustomException();
但我没有遇到关于 Entity
class.
的错误
Caused by: java.lang.NoClassDefFoundError: com/techdisqus/exception/MyCustomException
请注意 IF 条件将 NOT 执行 因为我正在传递命令参数为 test
为什么抛出异常导致加载永远不会执行的 MyCustomException
但 JVM 不会加载任何其他常规 class 除非满足条件,如此处 Entity
class 这里。请检查下面的 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");
}
}
}
感谢帮助
(这是有根据的猜测;我绝不是 JVM 内部专家)
我假设错误发生在 verification 期间,当加载的 class 进行一些健全性检查时,运行时可以稍后做出一些假设。
其中一项检查是字节码指令的类型检查。具体来说 athrow
:
An athrow instruction is type safe iff the top of the operand stack matches Throwable.
所以此时,class加载器必须加载MyCustomException
以检查它是否扩展Throwable
我有以下 classes.
我使用 javac 和 运行 Driver
class.[=30= 手动编译了 classes ]
稍后 删除了 entity.class
和 MyCustomException.class
以及 运行 应用程序,如下所示。
java Driver test
以下错误是关于缺少 MyCustomException
而不是关于 Entity
class 的。所以,不清楚为什么 JRE 抱怨 MyCustomException
class 而不是 Entity
class。
确实我已经删除了代码 throw new MyCustomException();
但我没有遇到关于 Entity
class.
Caused by: java.lang.NoClassDefFoundError: com/techdisqus/exception/MyCustomException
请注意 IF 条件将 NOT 执行 因为我正在传递命令参数为 test
为什么抛出异常导致加载永远不会执行的 MyCustomException
但 JVM 不会加载任何其他常规 class 除非满足条件,如此处 Entity
class 这里。请检查下面的 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");
}
}
}
感谢帮助
(这是有根据的猜测;我绝不是 JVM 内部专家)
我假设错误发生在 verification 期间,当加载的 class 进行一些健全性检查时,运行时可以稍后做出一些假设。
其中一项检查是字节码指令的类型检查。具体来说 athrow
:
An athrow instruction is type safe iff the top of the operand stack matches Throwable.
所以此时,class加载器必须加载MyCustomException
以检查它是否扩展Throwable