Skip to content

Raise Specific Error

Sourcery comment id: raise-specific-error

Description

Raise a specific error, so that callers of the code can handle the error appropriately.

Pattern

if incorrect_value():
    raise Exception
if incorrect_value():
    raise BaseException
if incorrect_value():
    raise Exception("some custom error message")

Possible Fix

You can use one of the built-in exceptions of the standard library:

if incorrect_value():
    raise ValueError

Or you can define your own exceptions deriving from a standard library exception:

if incorrect_value():
    raise SpecificIncorrectValueError

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
Back to top