请告诉我以下情况之间的区别:
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
}
}
这种情况下没有编译错误和
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
}
}
有编译错误
最佳答案
您现在在问题中拥有它的方式使其有效,因为 T
推断为 RuntimeException
(我记得这是因为 @SneakyThrows
):
private static < T extends Throwable > void doThrow(Throwable ex) throws T {
throw (T) ex;
}
基本上是 JLS
说如果你声明了一个具有 throws XXX
的方法,其中 XXX
的上限是 Exception
或 Throwable
, XXX
推断为 RuntimeException
.
关于java - 接下来的情况有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62958419/