Avoid Exception Hierarchies

Jakob Jenkov
Last update: 2014-05-26

You may have noticed that the exception handling template shown earlier in this tutorial, only uses a single exception class. There are no exception hierarchies. The reason I have avoided exception hierarchies, is because they don't really add much value to the template. Allow me to explain why I think so.

If you are not familiar with exception hierarchies, I have explained how they work in Java, in the text Exception Hierarchies

A Hierarchy is an Insufficient Categorization of Exceptions

Exception hierarchies are basically a way of categorizing exceptions. The standard Java API's typically categorize exceptions after what caused the exception. Like IOException,

However, as you have seen in this tutorial, there are several parameters that are needed to determine how to handle an exception, and not just its original cause. Thus, the categorization a hierarchy provides is insufficient to carry all the necessary information needed to handle an exception.

Proper exception handling requires both knowledge about the type of error (internal, client, service), the context in which the exception occurred, the severity etc. All that cannot be fitted into a single categorization.

Since not all information needed in an exception can be contained in an exception hierarchy, it is easier to just leave out the hierarchy completely, and just use a single exception class.

Hierarchies Clutters Exception Propagation

Leaving out the exception hierarchy also makes exception propagation easier. If a method can throw 3 different exceptions, which all extend the same superclass, should your method declare each of the 3 different exception subclasses, or just the exception superclass?

When there is only a single exception used in your application, you will always just propagate that up the call stack, if your method propagates the exception rather than handling it locally.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next