I know that generic types cannot extends Throwable and I understand that this doesn't make sense because type erasure (exceptions are thrown only at runtime) and other subtle things.
However Java allows a type parameter to be bounded by Throwable in fact the following code is legal
class MyClass<T extends Throwable> { /*body of the class */ }
What is illegal is the use of the T
parameter in a catch clause
try { //do something that throws exception // }
catch(T e) /* ILLEGAL!!! DOESN'T COMPILE */ {}
The only reason that I can understand about this constraint is that the type parameter, because erasure, is replaced by its bounding type, in this case Throwable
.
But type parameters could be bounded also by more than one bounding type so I could have this situation
class MyClass<T extends Object & Throwable> [*]
in such case T
is replaced after erasure by Object
and I know that an Object
(that is not of type Throwable
) variable cannot be inside a catch clause.
Let me know if this is the reason about this Java constraint. Thanks.
EDIT:
[*] As davidxxx make me notice, this class declaration doesn't compile because Throwable
is not an inteface.