Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Exception Handling

Exception Handling

The do's and do not's of exception handling and throwing, specifically with Java and Spring.

Nathan Kleyn

November 28, 2013

More Decks by Nathan Kleyn

Other Decks in Programming


  1. When an exception is caught, you could add code to

    check for another class that could this exception by returning a more specific message, defaulting to a standard message if one could not be found.
  2. These classes would effectively catch the exception and return a

    pretty message to the client. They have full access to the exception.
  3. A log should be made when an exception wasn’t handled

    by a specific class: I wasn't able to find a custom ExceptionHandler for the exception '{}' are you sure you want to handle this with the GlobalExceptionHandler? exception: {}
  4. Do not use Exceptions for flow control. They are for

    exceptional circumstances, it’s all in the name.
  5. public ModelAndView successfulLoginCallback(...) throws ... { try { SocialOAuthResult loginResult

    = login(…); } catch (RegistrationDetailsRequiredException e) { … } catch (AccountRestrictedException e) { … } }
  6. public ModelAndView successfulLoginCallback(…) throws … { UserLoginResult regResult = login(…);

    if (regResult.isPartiallyRegistered()) { … } else if (regResult.isRestrictedAccount()) { … } }
  7. If you have to use an exception, add it to

    the GlobalExceptionHandler - even if you don’t think it will ever go uncaught.
  8. Do not catch Throwable. If you find yourself needing to

    do this, please ask the team to weigh in - chances are, you’re doing it wrong.
  9. If you don’t preempt every possible exception, and everybody follows

    the rules, you’ll have only missed something truly exceptional anyway!
  10. Catch exceptions just to log and then rethrow them if

    iffy. Try to come up with a cleaner solution.