Skip to content

Raise-Specific-Error

Sourcery rule id: raise-specific-error

Description

Raise a specific error instead of the general Exception or BaseException

Match

raise Exception

Explanation

If a piece of code raises a specific exception type rather than the generic BaseException or Exception, the calling code can:

  • get more information about what type of error it is
  • define specific exception handling for it

This way, callers of the code can handle the error appropriately.

How can you solve this?

So instead of having code raising Exception or BaseException like

if incorrect_input(value):
    raise Exception("The input is incorrect")

you can have code raising a specific error like

if incorrect_input(value):
    raise ValueError("The input is incorrect")

or

class IncorrectInputError(Exception):
    pass


if incorrect_input(value):
    raise IncorrectInputError("The input is incorrect")