org.sonar.l10n.py.rules.python.S5754.html Maven / Gradle / Ivy
This rule raises an issue when a bare except:
, an except BaseException
or an except SystemExit
block does
not re-raise the exception caught.
Why is this an issue?
A SystemExit
exception is raised when sys.exit()
is called. This exception is used to signal the interpreter to
exit. The exception is expected to propagate up until the program stops. It is possible to catch this exception in order to perform, for example,
clean-up tasks. It should, however, be raised again to allow the interpreter to exit as expected. Not re-raising such exception could lead to
undesired behaviour.
A bare except:
statement, i.e. an
except
block without any exception class, is equivalent to except BaseException
. Both statements will catch every
exceptions, including SystemExit
. It is recommended to catch instead a more specific exception. If it is not possible, the exception
should be raised again.
It is also a good idea to re-raise the KeyboardInterrupt
exception. Similarly to
SystemExit
,KeyboardInterrupt
is used to signal the interpreter to exit. Not re-raising such exception could also lead to
undesired behaviour.
How to fix it
Re-raise SystemExit
, BaseException
and any exceptions caught in a bare except
clause.
Code examples
Noncompliant code example
try:
...
except SystemExit: # Noncompliant: the SystemExit exception is not re-raised.
pass
try:
...
except BaseException: # Noncompliant: BaseExceptions encompass SystemExit exceptions and should be re-raised.
pass
try:
...
except: # Noncompliant: exceptions caught by this statement should be re-raised or a more specific exception should be caught.
pass
Compliant solution
try:
...
except SystemExit as e:
...
raise e
try:
...
except BaseException as e:
...
raise e
try:
...
except FileNotFoundError:
... # Handle a more specific exception
Resources
Documentation
- PEP 352 - Required Superclass for Exceptions
- Python Documentation - Built-in exceptions
- Python Documentation - The
try
statement
- CWE - CWE-391, Unchecked Error Condition