Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

According to the Java Language Sepecification, 3rd edition:

It is a compile-time error if a generic class is a direct or indirect subclass of Throwable.

I wish to understand why this decision has been made. What's wrong with generic exceptions?

(As far as I know, generics are simply compile-time syntactic sugar, and they will be translated to Object anyway in the .class files, so effectively declaring a generic class is as if everything in it was an Object. Please correct me if I'm wrong.)

1 Answer

0 votes
by (46k points)

As mark said, the types are not reifiable, which is a problem in the following case:

try {

   doSomeStuff();

} catch (SomeException<Integer> e) {

   // ignore that

} catch (SomeException<String> e) {

   crashAndBurn()

}

Both SomeException<Integer> and SomeException<String> are erased to the same type, there is no way for the JVM to distinguish the exception instances, and therefore no way to tell which catch block should be executed.

Related questions

0 votes
1 answer
asked Feb 20, 2020 in Java by angadmishra (6.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...