Search code examples
javaexceptionthrowable

What's the difference between the next situations


Please, tell me 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
    }
}

There is no compilation error in this case

AND

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
    }
}

There is compilation error


Solution

  • The way you have it right now in the question, makes it works because T is inferred to be a RuntimeException( I remember this because of @SneakyThrows):

    private static < T extends Throwable > void doThrow(Throwable ex) throws T {
         throw (T) ex;
    }
    

    Basically the JLS says that if you declare a method that has throws XXX, where the upper bound of XXX is Exception or Throwable, the XXX is inferred to a RuntimeException.