一个方法的 throws
列表在编译时显然起着作用。但是在运行时它是否有任何影响呢?
例如,如果我有一个没有 throws
列表的方法,并使用黑魔法字节码召唤并抛出一个 IncrediblyCheckedException
,它会毫不犹豫地抛出吗?还是运行时验证器会注意到这一点,而抛出错误或其他东西呢?
Thread.currentThread.stop(new Exception());
代码可以在任何地方编写,而该行代码将会抛出异常。
上述代码将从本地代码中抛出异常,但这里有另一个使用普通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;
}