try-consider-else (TRY300)#
Derived from the tryceratops linter.
What it does#
Checks for return statements in try blocks.
Why is this bad?#
The try-except statement has an else clause for code that should
run only if no exceptions were raised. Using the else clause is more
explicit than using a return statement inside of a try block.
Example#
import logging
def reciprocal(n):
try:
rec = 1 / n
print(f"reciprocal of {n} is {rec}")
return rec
except ZeroDivisionError:
logging.exception("Exception occurred")
Use instead:
import logging
def reciprocal(n):
try:
rec = 1 / n
except ZeroDivisionError:
logging.exception("Exception occurred")
else:
print(f"reciprocal of {n} is {rec}")
return rec