Skip to content

Remove Redundant Exception

Sourcery refactoring id: remove-redundant-exception

Description

Remove redundant exceptions from an except clause.

Before

except(ValueError, Exception):
    logger.log("error")

After

except Exception:
    logger.log("error")

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 Exception class.
  • All user-defined exceptions should also be derived from the Exception class.
  • 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.