Skip to content

Merge Exception Handlers

Sourcery refactoring id: merge-except-handler

Description

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

Before

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

After

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

Explanation

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.