Why can't you catch a type parameter in Java?

时间:2015-11-12 11:52:57

标签: java generics try-catch

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?

0 个答案:

没有答案