views:

171

answers:

2
class Bouncy<T> extends Throwable {     
}
// Error: the generic class Bouncy<T> may not subclass java.lang.Throwable

Why doesn't Java support generic Throwables?

I realize that type erasure complicates certain things, but obviously Java gets by with a lot already, so why not push it one more notch and allow generic Throwables, with comprehensive compile-time check for potential problems?


I feel like the type erasure argument is rather weak. Currently, we can't do:

void process(List<String> list) {
}

void process(List<Integer> list) {
}

Of course, we get by without it. I'm not asking that we should be able to do catch Bouncy<T1> and Bouncy<T2> in the same try block, but if we use them in disjoint contexts with strict compile-time enforceable rules (which is pretty much the way generics works right now), wouldn't it be workable?

+6  A: 

Java Language Specification 8.1.2 Generic Classes and Type Parameters:

This restriction is needed since the catch mechanism of the Java virtual machine works only with non-generic classes.

Personally, I think it's because we can't get any benefits of generics inside a catch clause. We can't write catch (Bouncy<String> ex) due to type erasure, but if we write catch (Bouncy ex), it would be useless to make it generic.

axtavt
Any idea why it happens that way?
zneak
+3  A: 

Type erasure. Runtime exception type has no generics information. Thus you cannot do

} catch( Mistake<Account> ea) {
  ...
} catch( Mistake<User> eu) {
...
}

all you can do is

catch( Mistake ea ) {
  ...
}

And type erasure is how it was decided to preserve the backward compatibility when Java was moving from 1.4 to 1.5. Many people was unhappy then, and rightfully so. But having in mind the amount of deployed code, it was unthinkable to break code that worked happily in 1.4.

Vladimir Dyuzhev