接下来的情况有什么区别

What's the difference between the next situations

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

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 的上限是 ExceptionThrowableXXX 被推断为 RuntimeException.