Exception handling tips

Clean Code 7

Errors should never pass silently.
Unless explicitly silenced.

~The Zen of Python, by Tim Peters

Create custom exception classes

Your exceptions should say exactly what went wrong. While those provided by programming languages are good, they are too general and are not specific to your codebase.

Oversimplified example:

  • Bad: Exception(“number is smaller than 0”)
  • Better: SpeedException(“Speed should not be smaller than 0”)

The reason you want to do this is that you can handle different types of exceptions in different ways and it is much easy to know exactly what went wrong from the logs.

In most programming languages creating exception is easy. Just inherit from the main Exception class which should be enough for most cases.

Custom Exception class also makes your logs easier to read.

Always know why you are catching an exception…

TODO: Find and Add YouTube video attribution

… or just don’t catch it (throws to the caller)

if you are not going to do anything with the exception don’t catch it just throw it.

Don’t add throw exception in the catch block. Use throws while declaring the function instead.

For Unsupported Operations

In if-else statements or switch cases, it is always good to have a default case which will execute if no other condition is true.

If something is not possible or not supported then:

  • throw (Java): UnsupportedOperationException
  • raise (Python): NotImplementedError

Global exception handling

These allow you to have the same exception handling mechanism in case you have not explicitly handled the exception.

The most basic thing to do here is logging the exception.

Spring (Java): @ControllerAdvice

Previous: Avoid inventing algorithms and data structures

Next: Leave code better than you found it.

Index: Tips on writing Clean Code



Ankush Choubey: Full Stack Dev-Cloud/Microservices

25 y.o full stack developer from Mumbai who loves Full Stack Development and Deep Learning. Original Blog at ankushchoubey.com