How we detect
- an except instruction is immediately followed by a colon, i.e does not specify any exception class name (case of a bare except).
- an except instruction is catching the BaseException class
- an “except Exception:” is in first position or not in last position.
bad
def divide(a, b):
try:
result = a / b
except:
result = None
return result
good
def divide(a, b):
result = None
try:
result = a / b
except ZeroDivisionError:
print "Type error: division by 0."
except TypeError:
# E.g., if b is a string
print "Type error: division by '{0}'.".format(b)
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
else:
# Excecutes if no exception occured
print "No errors"
finally:
# Executes always
if result is None:
result = 0
return result
Why you should care
pythonic
. By not specifiycing an exception type, you might also loose information about the error itself.
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).
Business Impacts
It is advised to avoid risky catches because they can reduce the productivity of the application and waste plenty of team’s time and effort in the process.
CAST recommendations
Highlight considerations:
- If you really want to catch SystemExit or KeyboardInterrupt, do it explicitly, not with a bare except statement.
- generic catch “except Exception” will be tolerated by Highlight tool, only if it is preceded by at least one non-generic except statement, and is in last position.
References
https://www.quantifiedcode.com/knowledge-base/correctness/Avoid%20untyped%20exception%20handlers/3JwOg9ad
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.