According to the Java Language Sepecification, 3rd edition:
It is a compile-time error if a generic class is a direct or indirect subclass of
Throwable
.
I wish to understand why this decision has been made. What's wrong with generic exceptions?
(As far as I know, generics are simply compile-time syntactic sugar, and they will be translated to Object
anyway in the .class
files, so effectively declaring a generic class is as if everything in it was an Object
. Please correct me if I'm wrong.)
As mark said, the types are not reifiable, which is a problem in the following case:
try {
doSomeStuff();
} catch (SomeException<Integer> e) {
// ignore that
} catch (SomeException<String> e) {
crashAndBurn()
}
Both SomeException<Integer>
and SomeException<String>
are erased to the same type, there is no way for the JVM to distinguish the exception instances, and therefore no way to tell which catch
block should be executed.