How does exception handling interact with generics and type erasure, specifically regarding why you cannot catch a generic type parameter as an exception type (catch (T e))?
Short answer
Due to type erasure, a generic type parameter T has no runtime representation the JVM could use to determine whether a thrown exception actually matches T at a specific catch site (the compiled bytecode has no way to check 'is this exception an instance of whatever T happens to…
Advertisement
AModel answer
Due to type erasure, a generic type parameter T has no runtime representation the JVM could use to determine whether a thrown exception actually matches T at a specific catch site (the compiled bytecode has no way to check 'is this exception an instance of whatever T happens to be for this particular invocation'), so Java simply disallows catch (T e) entirely as a compile-time error -- similarly, you cannot create a generic exception class (class MyException<T> extends Exception is illegal) since each distinct throwable type needs a genuine, fixed runtime identity for the exception-matching mechanism to function correctly, another manifestation of the same type erasure limitation that also prevents generic array creation.
// This does NOT compile -- illegal to catch a type parameter
public <T extends Exception> void doSomething() {
try {
riskyOperation();
} catch (T e) { // COMPILE ERROR: cannot catch a type variable
// ...
}
}
// Also illegal: a generic exception class
// class MyException<T> extends Exception { } // COMPILE ERRORReal-world example
A generic retry-wrapper utility attempting to catch a type-parameterized exception type (to apply generic retry logic for a caller-specified exception class) hits a compile error and instead has to accept a Class<T> token parameter combined with an isInstance() check at runtime, working around type erasure's fundamental limitation here.
Likely follow-ups
- How would you work around this limitation using a Class<T> token parameter and isInstance() checking instead?
- What's the connection between this restriction and the earlier-discussed inability to create generic arrays?
Related topics