Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked vs. Unchecked Exceptions in Service Layer

Tags:

People also ask

What is the difference between checked and unchecked exception?

A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn't required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.

Why do we have checked and unchecked exceptions?

Remember the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the control of the program, while unchecked exceptions are occurred during runtime and are used to indicate programming errors.

Why checked exceptions are checked at compile time?

Checked exceptions are checked at compile time to ensure you are handling them, either by catching them or declaring the containing method throws the exception. At runtime, there is no distinction between checked and unchecked exceptions: they are treated identically by the JVM.


I work on a project with a legacy service layer that returns null in many places if a requested record does not exist, or cannot be accessed due to the caller not being authorized. I am talking about specific records requested by ID. For instance, something like:

UserService.get(userId);

I have recently pushed to have this API changed, or supplemented with a new API that throws exceptions instead. The debate over checked vs unchecked exceptions has ensued.

Taking a note from the designers of JPA/Hibernate et all., I have suggested that unchecked exceptions may be most appropriate. My argument being that users of the API cannot be reasonably expected to recover from these exceptions and in 99% of the cases we can at best notify the application user that some error has occurred.

Having runtime exceptions propagate up to generic handling mechanisms will obviously reduce a lot of the complexity and required branch handling involved in dealing with edge-case exceptions. But, there is a lot of concern surrounding such an approach (rightly so).

Why have the designers of such projects as JPA/EJB and Hibernate selected to go with an unchecked exception model? Is there a very good justification for it? What are the pros/cons. Should developers using these frameworks still handle the runtime exceptions close to where they are thrown with something like adapter wrappers?

I hope answers to these questions can help us to make the "right" decision regarding our own service layer.