try-except-raise / W0706ΒΆ
Message emitted:
The except handler raises immediately
Description:
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:
try:
1 / 0
except ZeroDivisionError as e: # [try-except-raise]
raise
Correct code:
remove_try_except.py
:
# The try except might be removed entirely:
1 / 0
specialized_exception.py
:
# Another more detailed exception can be raised:
try:
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):
try:
return some_calculation(a, b)
except ZeroDivisionError:
raise
except ArithmeticError:
return float('nan')
The pylint is able to detect this case and does not produce error.
Created by the exceptions checker.