Alex Rivera | Logout

Is it wise to use generics for exceptions?

Asked 2011-07-25T15:12:55.487
20

My team is in the middle of cleaning up our use of throws Exception and either removing or replacing them with specific exceptions.

A common throws is because an entity was not found. Should we be throwing a generic NotFoundException or a specific SomeClassNotFoundException for each entity class?

If we should be throwing a specific exception, should we be creating a specific Exception class for each entity type? Can we safely use generics? Like this class NotFoundException<T extends EntityBaseClass> extends Exception and then the constructor takes care of declaring what Entity type we're dealing with?

If we should be throwing a specific exception and not using generics, should those exceptions extend or implement a NotFoundException abstract class or interface?

Edit
Report

1 Answer

30

It's not allowed to make exceptions generic - it won't compile (JLS ยง8.1.2):

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

Since type parameters of generics are erased at runtime, there is no way to distinguish between generic exceptions with different type parameters in the catch clause, thus generic exceptions are not supported. So, you actually have no choice regarding using generic exceptions.

answered 2011-07-25T15:16:43.583

Your Answer