try-except-raise / W0706#

Message emitted:

The except handler raises immediately


Used when an except handler uses raise as its first or only operator. This is useless because it raises back the exception immediately. Remove the raise operator or the entire try-except-raise block!

Problematic code:

    1 / 0
except ZeroDivisionError as e:  # [try-except-raise]

Correct code:

# The try except might be removed entirely:
1 / 0

# Or another more detailed exception can be raised:
    1 / 0
except ZeroDivisionError as e:
    raise ValueError("The area of the rectangle cannot be zero") from e

Additional details:

There is a legitimate use case for re-raising immediately. E.g. with the following inheritance tree:

+-- ArithmeticError
     +-- FloatingPointError
     +-- OverflowError
     +-- ZeroDivisionError

The following code shows valid case for re-raising exception immediately:

def execute_calculation(a, b):
        return some_calculation(a, b)
    except ZeroDivisionError:
    except ArithmeticError:
        return float('nan')

The pylint is able to detect this case and does not produce error.

Created by the exceptions checker.