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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With