Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does spring prefer unchecked exceptions?

while studying spring I stumbled over this question. Java supports both checked and unchecked exceptions. Language-agnostic design guidelines seems to favour unchecked exceptions. This question is why using an inversion of control-container like Spring implies that I should only use unchecked exceptions.

like image 610
Jesper Avatar asked Oct 25 '18 07:10

Jesper


1 Answers

The question "why using an inversion of control-container like Spring implies that I should only use unchecked exceptions" is a bit strange. And I am not sure that using IoC implies you should use unchecked exceptions. Checked vs unchecked is in the end matter of context and opinion.

My view on this:

Exceptions can be categorized in checked and unchecked exceptions. That simply means that some exceptions, the checked ones, require us to specify at compile time how the application will behave in case the exception occurs. The unchecked exceptions do not mandate compile time handling from us. To create such exceptions, you extend the RuntimeException class which is a direct subclass of Exception. An old and common guideline when it comes to checked vs unchecked is that runtime exceptions are used to signal situations which the application usually cannot anticipate or recover from, while checked exceptions are situations that a well-written application should anticipate and recover from.

I am an advocate of only using runtime exceptions. And if I use a library that has a method with a checked exception, I create a wrapper method that turns it into a runtime. Why not checked exceptions then? Uncle Bob, in his “Clean Code” book, argues that they break the Open/Closed principle, since a change in the signature with a new throws declaration could have effects in many levels of our program calling the method.

I have written a post about dealing with exceptions, you could check it out if interested: https://dzone.com/articles/how-to-deal-with-exceptions

like image 80
martidis Avatar answered Sep 21 '22 05:09

martidis