Леш*_*кки 5 java exception throwable
请告诉我以下情况之间的区别:
public class Test {
private static < T extends Throwable > void doThrow(Throwable ex) throws T {
throw (T) ex;
}
public static void main(String[] args) {
doThrow(new Exception()); //it's ok
}
}
Run Code Online (Sandbox Code Playgroud)
这种情况下没有编译错误
和
public class Test {
private static < T extends Throwable > void doThrow(Throwable ex) throws Throwable {
throw (T) ex;
}
public static void main(String[] args) {
doThrow(new Exception()); //unhandled exception
}
}
Run Code Online (Sandbox Code Playgroud)
有编译错误
你现在在问题中的方式使它起作用,因为T被推断为RuntimeException(我记得这是因为@SneakyThrows):
private static < T extends Throwable > void doThrow(Throwable ex) throws T {
throw (T) ex;
}
Run Code Online (Sandbox Code Playgroud)
基本上,JLS如果您声明一个具有 的方法throws XXX,其中 的上限XXX是Exceptionor Throwable,则XXX会被推断为 a RuntimeException。