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.
Related Rules¶
- remove-redundant-except-handler to
remove unreachable
except
blocks - remove-redundant-exception to clean up the tuple of an except clause
- use-contextlib-suppress instead of empty
except
blocks - do-not-use-bare-except to always specify which
errors an
except
block is handling