gpt4 book ai didi

java - 接下来的情况有什么区别

转载 作者:行者123 更新时间:2023-12-01 11:57:36 25 4
gpt4 key购买 nike

请告诉我以下情况之间的区别:

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 的上限是 ExceptionThrowable , XXX推断为 RuntimeException .

关于java - 接下来的情况有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62958419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com