My question is a follow-up to this question:
Why doesn't Java allow generic subclasses of Throwable?
The question was answered perfectly, but only on indirect generic exception, that's:
public class MyException<T> extends Exception {
What was left void, is direct generics:
public static <T extends Exception> void checkForException(Class<T> exType) {
try {
// some code
} catch (T e) {
e.printStackTrace();
}
}
Why is this not allowed?
Though, the only reason I could think this is not allowed, is that T
could be a type, that is also explicitly caught:
// if T is IOException
catch(T e) { }
catch(IOException e) { }
But is this a good reason to block it? The same effect, could as well be done without generics too:
catch(Exception e) { }
catch(IOException e { }
Here's the documentation of the above restriction.