Skip to content

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”

Remove redundant exceptions from an except clause.

try:
int("not an int")
except (ValueError, Exception):
logger.log("error")
try:
int("not an int")
except Exception:
logger.log("error")

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.