Exception handling : 3 ways illustrated

min-maxx
Javarevisited
Published in
4 min readOct 14, 2021

--

We will explore several ways of handling exception so that you can choose your favorite for your application.

Photo by Nong Vang on Unsplash

It is a subject little treated and yet omnipresent in our applications. We will see different ways of handling errors via examples. The goal is to allow you to compare several approaches. For tech lead, it is important to have options in mind.

In the following examples, I split the snippet code into layers: model, service, controller. The entry point is the controller:

CONTROLLER --> SERVICE --> MODEL

I consider the Service as the entry point into the business code. In other words, it’s our business API. It is at this level that the business contract is determined via the method signatures and the model.

The Controller just adapts the business contract to outside world.

I have intentionally omitted the other classes of services to keep things concise. The treatment they make and the exceptions they make do not change between the examples.

The principle shared by all the examples is to minimize non-business code (aka accidental complexity) and to make the contract explicit.

After each example, I add some remarks and the possible alternatives.

With vanilla Exception

--

--