Skip to content

Merge Exception Handlers

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: merge-except-handler

Section titled “Sourcery refactoring id: merge-except-handler”

Merge exception handlers with the same body into a single except handler.

try:
f = open("myfile.txt")
s = f.readline()
i = int(s.strip())
except OSError as err:
logger.exception("Error while reading myfile.txt")
raise
except ValueError as err:
logger.exception("Error while reading myfile.txt")
raise
try:
f = open("myfile.txt")
s = f.readline()
i = int(s.strip())
except (OSError, ValueError) as err:
logger.exception("Error while reading myfile.txt")
raise

By merging except handlers with the same body we remove duplicate code. This makes it easier to read, and when changing the logic we won’t accidentally change it in only one place instead of both.