The recommended approach

We recommend an approach very similar to the one used by Spring Framework. When deciding what exceptions to throw from a method, always think about the consumer of the method.

Can the consumer of the method do something about the exception?

In the preceding example, if the execution of the query failed, the consumer method would not be able to do anything except show an error page to the user. In that kind of a scenario, we should not complicate things and force the consumer to handle the exception.

We recommend the following approach to exception handling in applications:

  • Think about the consumer. If the consumer of the method cannot do anything useful (except logging or showing an error page) about the exception, make it unchecked.
  • In the topmost layer, typically the presentation layer, have catch all exception handling to display an error page or to send an error response to the consumer. Refer to @ControllerAdvice in Chapter 3, Building Web Application with Spring MVC for more details about implementing catch all exception handling.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset