I'm wondering why the following code works:
public static void throwUnchecked(Exception e) {
TestGenericExceptionCast.<RuntimeException> doThrowUnchecked(e);
}
@SuppressWarnings("unchecked")
private static <T extends Exception> void doThrowUnchecked(Exception toThrow) throws T {
throw (T) toThrow;
}
public static void main(String[] args) {
throwUnchecked(new Exception());
}
Why can the exception be cast to RuntimeException via generics?
Got it:
No cast happens at all, because no object is ever assigned to something with type T.
The compilers gets tricked and can't see that it's a checked exception anymore.