Exception handling and Exception throwing principles

willemodendaal
The Curious Coder
Published in
2 min readJun 23, 2020

Return exceptions for exceptional situations. Return result objects for other non-happy-path results.

How to identify when is something “exceptional”?

  • Exceptional is usually technical in nature, not domain related. (eg. Null ref errors, array out of bounds, connectivity issues, etc.)
  • Domain errors should usually be returned as result objects. (eg. No money left in account, booking slot already reserved, etc.)

The “keep your head down” principle:

  • Beware of writing code that assumes things about the caller. A Manager, for example, should not assume how the UI layer behaves (eg. The UI will make sure the user can’t pass this-or-that-kind-of object to update).
  • However, It’s ok to make some assumptions about other code in the same layer, but even this couples your code to other code. Standalone is better.

The “healthy boundaries” principle:

  • “If someone uses me in the wrong way, I’m allowed to say ‘No!’”. (eg. throw an exception on invalid argument).
  • “But I should be clear about what my boundaries are.” (tests, comments, annotations, etc).

The “savvy courier” principle:

  • “When I call external resources (filesystem, network, api, etc), then I should expect transient errors and handle them, usually with a retry with back-off policy, culminating in a hard exception if all retries fail.”

The “let it bubble up” principle:

  • “If I call other code, I can expect it to behave in the expected way.”
  • No need to safeguard against unexpected exceptions. We expect the method we’re calling to throw an exception if something weird happens, when it can’t behave in the expected way. In most cases we just let this Exception bubble up to our root exception handling code.
  • We need to make sure our root code always catches and logs exceptions.
  • We need to make sure our user interfaces can always show that “something went wrong”.

--

--

willemodendaal
The Curious Coder

Full stack developer and technology geek; Livin’ the dream!