Be a Developer, not a Blender

How can we use Exceptions Correctly?

Unfortunately it’s easy to find exception handling code that does more harm than good. Take a look at the code below:

try{
    myObject.doSomething();
} catch(MyExceptionOne one){
    sendErrorSmsToCustomer();
    defineOldPlanToCustomer();
    sentToScreenOne();
} catch(MyExceptionTwo two){
    sendErrorEmailToCustomer();
    defineNewPlanToCustomer();
    sentToScreenTwo();
} catch(Exception genericException){
    sendErrorSmsToCustomer();
    sendErrorEmailToCustomer();
    sentToScreenThree();
}

About the code above:

  • The exception is handling the request flow
  • The exception is responsible for the business rule
  • The method is huge and makes the reading difficult
  • If a developer uses a lot of checked exceptions he will have a verbose and harder to read code

An exception should be seen as an error notification to be sent to the user, it should not do business actions.

How could we improve the code above? Notice that for the Business Exception we would find a code like:

if (isNotValid(myObject)) {
    throw MyExceptionOne(“some info”);
}

Instead of just throwing the exception, the developer should execute the rollback actions before:

if (isNotValid(myObject)) {
    rollbackService.doRollback(myObject);
    throw MyExceptionOne(“some info”);
}

Why are we processing a rollback before the exception has been thrown? Imagine that a developer invokes the method myObject.doSomething() in another class; how will the developer know what actions must be done in the catch? The practice of adding business code in a catch block would cause duplicated code or inconsistency in the way that exceptions are handled.

Another good practice is: do not hide an exception. Do not write a code like below:

try{
} catch (Exception ex) {
    // do nothing
    // or
    // will never get in here
}

If you do not print the error stack you will never get to know if that catch block is executed. Log all your exceptions, make sure to write it  where someone will see it.

Conclusion

Always have in mind that a catch block should not have business rules. Keep a catch code always simple, if possible set only the text to be displayed to the user and/or error logging.

2 thoughts on “Be a Developer, not a Blender

Leave a Reply to uaihebert Cancel reply