方法的throws
列表显然在编译过程中发挥作用。然而,它在运行时有任何影响吗?
例如,如果我有一个没有throws
列表的方法,并使用暗字节码魔术来召唤并抛出一个IncrediblyCheckedException
,它会毫无疑问地抛出它还是运行时 validator 注意到这一点并抛出错误或其他东西?
最佳答案
它对运行时没有任何影响。恰当的例子:
Thread.currentThread.stop(new Exception());
可以写在任何地方,这行代码会抛出异常。
上面的代码将从 native 代码中抛出异常,但这里是另一个使用普通 Java throw
的技巧:
public static void main(String[] args) {
CurrentClass.<RuntimeException>sneakyThrow(new Exception());
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void sneakyThrow(Throwable t) throws E {
throw (E)t;
}
关于java - 抛出 vs Java 字节码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21329832/