3

Java does not let you catch type parameters. For example, the following (contrived) code causes a compile-time error:

private static <E> String callMethod() {
    try {
        return SomeUtilityClass.<E>method();
    catch(E e) {
        doSomething();
    }
}

Why is this? Surely the above code is just equivalent to:

private static <E> String callMethod() {
    try {
        return SomeUtilityClass.<E>method();
    catch(Throwable e) {
        if (e instanceof E) {
            doSomething();
        } else {
            throw e;
        }
    }
}

Are the above two code snippets equivalent? If so, there is no problem for the Java compiler to generate bytecode for the first one. Why does the Java language prevent it?

Adam Burley
  • 5,551
  • 4
  • 51
  • 72
  • I do not think this question is duplicate! The OP is not asking for a workaround. The OP apparently understands that the specification does not allow it, but he does not understand the reason behind it - as he suggests a plausible conversion of the code into something understandable by the JVM. – Honza Zidek Nov 13 '15 at 10:29
  • I already deleted this question so I don't know why it has come back. The issue is that in fact `e instanceof E` does not compile. So you have to pass in the `exceptionClass` and use things like `exceptionClass.isInstance` which I couldn't reasonably expect the compiler to insert. – Adam Burley Nov 13 '15 at 11:41

0 Answers0