Basic Rules

Typically, you wrap a Try/Catch block around your functionality so that all unexpected situations flow down into the Catch block.

Try   --> whatever (unexpected) happens here
Catch --> will be handled here

Typically, you wrap a Try/Catch block around your functionality so that all unexpected situations flow down into the Catch block. There are some common patterns which are used independly of the programming environment or language.

  • DO use only one Try/Catch block per function / process

  • DO NOT handle unexpected situations as part of your business logic (for example, in a sub-process). Whenever you are coming across a situation in your logic, where you do not know how to recover you throw an Exception or let the Exception happen.

Delegating Exception Handling

While you might use multiple try/catch block only the top-level catch does the exception handling. "Lower" catch branches might implement some clean-up and terminate gracefully from the exception but they do not handle the exception itself, for example, by sending an e-mail. Normally, "lower" catch branches re-throw the exception to "bubble it up" to the highest handler.

Main Process 
  Try   --> subChild01()
  Catch --> Send E-Mail

subChild01()
  Try   --> Logic 
  Catch --> cleanup (close resources, set state etc.)
            re-throw exception --> will be caught in the Main Handler!

Anti-Pattern

WRONG: A sub-process catching and handling an exception: sending an e-mail.

RIGHT: Only the top-level process implements the exception handler (Catch block), while the sub-process let Exceptions happen.

This principle of delegating exception handling to parents is similar to real life:

If a child has a problem and it does not know how to solve it, it goes to its parents and asks them to handle it: simple escalation! (Imagine you let the children handle their problem themselves ...)

Last updated