Remove Redundant Exception
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: remove-redundant-exception
Section titled “Sourcery refactoring id: remove-redundant-exception”Description
Section titled “Description”Remove redundant exceptions from an except clause.
Before
Section titled “Before”try: int("not an int")except (ValueError, Exception): logger.log("error")try: int("not an int")except Exception: logger.log("error")Explanation
Section titled “Explanation”An except clause handles all instances of the defined exception, incl. its
subclasses. If an exception is a subclass of another exception, it’s redundant
to mention both explicitly in the except clause.
Note that:
- All built-in, non-system-exiting exceptions are derived from the
Exceptionclass. - All user-defined exceptions should also be derived from the
Exceptionclass. - It’s a good practice to have a base exception class for your application
(deriving from
Exception) and have your more specific custom exceptions derive from it.
Related Rules
Section titled “Related Rules”- merge-except-handler to merge except handlers with the same content
- remove-redundant-except-handler to
remove unreachable
exceptblocks - use-contextlib-suppress instead of empty
exceptblocks - do-not-use-bare-except to always specify which
errors an
exceptblock is handling