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:
importloggingdefsend_email():("Sending email")raiseConnectionError("Oops")try:send_email()except:# AVOID THISpass
Here’s what it looks like when you deal with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access