Chapter 22. Exceptions

Optimization hinders evolution. Everything should be built top-down, except the first time. Simplicity does not precede complexity, but follows it.

Alan Perlis

22.0 Introduction

Exceptions are an amazing mechanism to favor clean code by separating good use cases from errors and dealing with the latter elegantly. Sadly, some trendy languages like Go decided in the name of premature optimization to use the old return code mechanism, forcing a lot of if conditions (which many developers forget) and only providing high-level catchall exception handlers.

Exceptions are your best tool for separating concerns and help you separate the good path from the exceptional one, even for unforeseen situations. They create good flow control and fail fast. Nevertheless, they still require thoughtful consideration and proper handling to ensure their effectiveness and avoid potential pitfalls.

22.1 Removing Empty Exception Blocks

Problem

You have code ignoring some exceptions.

Solution

Don’t ignore exceptions. Handle them.

Discussion

“On Error Resume Next” was a very common practice some years ago. This violated the fail fast principle (see Chapter 13 “Fail Fast”) and created a ripple effect. You should catch the exception and deal with it explicitly. Here is an example ignoring exceptions:

import logging

def send_email():
  print("Sending email")
  raise ConnectionError("Oops")

try:
  send_email()
except:
  # AVOID THIS
pass

Here’s what it looks like when you deal with ...

Get Clean Code Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.