Recipe 5.1 · Python
No Empty Catch Blocks
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
A catch { } or catch (Exception) { } throws away the only evidence that something failed. The
code carries on with half-finished work: a file that wasn't written, a row that wasn't saved, a
customer who wasn't billed. Nobody finds out until the numbers don't add up.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Three ways to hide a failure with empty or swallowing catch blocks
Source: ImproveCode, Chapter 5, Recipe 5.1 "No Empty Catch Blocks"
Section: The way it's often written
Book page: 99-100 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Decimal() replaces decimal.Parse, os.remove replaces File.Delete, and a label
object stands in for the WebForms lblError control.
"""
from __future__ import annotations
import os
from decimal import Decimal
from typing import Any, Callable
def examples(
fields: list[str], temp_path: str, order: Any,
save_order: Callable[[Any], None], lbl_error: Any,
) -> Decimal:
# Not this: three ways to hide a failure.
try:
price = Decimal(fields[3])
except: # noqa: E722
price = Decimal(0) # bad data becomes a free product
try:
os.remove(temp_path)
except Exception:
pass # also hides a typo in the path
try:
save_order(order)
except Exception as ex:
lbl_error.text = str(ex) # the user sees it; nobody else does
return price
The improved recipe
Every catch must do one of four things: recover with a known fallback, translate the exception
into one with more context, log it at a boundary, or clean up and rethrow. Expected bad input
should not use exceptions at all.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Price file reader that logs bad rows and recovers only from expected errors
Source: ImproveCode, Chapter 5, Recipe 5.1 "No Empty Catch Blocks"
Section: The improved recipe
Book page: 100-101 -- original C# listing
Converted from C# to Python.
logging replaces ILogger; the TryParse/out pattern becomes a function returning
PriceRow | None; IOException/UnauthorizedAccessException map to OSError/PermissionError.
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from pathlib import Path
@dataclass(frozen=True)
class PriceRow:
sku: str
price: Decimal
class PriceFileReader:
def __init__(self, logger: logging.Logger | None = None) -> None:
self._logger = logger or logging.getLogger(__name__ + ".PriceFileReader")
def read(self, path: str) -> list[PriceRow]:
rows: list[PriceRow] = []
# Missing file or no permission: let it propagate.
# The caller decides; we have nothing useful to add.
with open(path, encoding="utf-8") as f:
for line_number, raw in enumerate(f, start=1):
line = raw.rstrip("\r\n")
# Bad data is expected, so it is not an exception.
row = self._try_parse(line)
if row is not None:
rows.append(row)
else:
self._logger.warning(
"Skipped line %s of %s: %s",
line_number, Path(path).name, line)
return rows
def delete_quietly(self, path: str) -> None:
try:
os.remove(path)
except FileNotFoundError:
pass # File.Delete does not throw for a missing file
except OSError as ex: # includes PermissionError
# Recover: a locked temp file is removed on the next run.
self._logger.debug("Could not delete %s", path, exc_info=ex)
@staticmethod
def _try_parse(line: str) -> PriceRow | None:
fields = line.split(",")
if len(fields) != 2 or len(fields[0]) == 0:
return None
try:
price = Decimal(fields[1].strip().replace(",", ""))
except InvalidOperation:
return None
if not price.is_finite() or price < 0:
return None
return PriceRow(fields[0].strip(), price)
How it works
Read has no try at all. If the file is missing, File.ReadLines throws
FileNotFoundException with the path in the message, and that is exactly what the caller and the
log need. Catching it here only to rethrow or return an empty list would make things worse: an
empty list looks like "no prices today."
Bad lines are an expected condition in any imported file, so the code tests for them with
TryParse instead of catching FormatException. That is faster, and it keeps exceptions for
things that are truly unexpected. The warning records the line number and content, so the person
who sent the file can fix it.
DeleteQuietly is a legitimate recovery. Failing to delete a temp file is harmless, and there is
a fallback (the next run tries again). The exception filter limits the catch to the two exception
types that mean "locked" or "no permission." A NullReferenceException from a bug, or an
ArgumentException from an invalid path, still escapes. The comment says why swallowing is safe,
and the debug log keeps a trail.
The rule of thumb: catch only what you can name, and only where you can do something about it. Everywhere else, let the exception travel up to the global handler (Recipe 5.4) or the job runner (Chapter 4, Recipe 4.6), which logs it once with full context.
Variations and pitfalls
catch (Exception)is fine at a true boundary: the top of a request, a background job loop, a message handler. Those places must log and keep the process alive. Deep inside business logic it almost always hides bugs.- Never catch
OperationCanceledExceptionas a failure. If the caller cancelled, let it go. When you do catch it, filter withwhen (ct.IsCancellationRequested). - Displaying
ex.Messageto users leaks internals (table names, file paths, server names) and does nothing for support. Show a reference number instead and log the details (Recipe 5.4). - To find the empty catches in a code base, search for
catch\s*(\(\s*Exception\s*\w*\s*\))?\s*\{\s*\}with your editor's regex search, then review each one. Most can simply be deleted. - Turn on analyzer rule CA1031 (do not catch general exception types) in new projects and suppress it, with a comment, at the few real boundaries.