This rule raises an issue when a bare
except BaseException or an
except SystemExit block does
not re-raise the exception caught.
Why is this an issue?
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
except: statement, i.e. an
except block without any exception class, is equivalent to
except BaseException. Both statements will catch every
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
KeyboardInterrupt is used to signal the interpreter to exit. Not re-raising such exception could also lead to
How to fix it
BaseException and any exceptions caught in a bare
Noncompliant code example
except SystemExit: # Noncompliant: the SystemExit exception is not re-raised.
except BaseException: # Noncompliant: BaseExceptions encompass SystemExit exceptions and should be re-raised.
except: # Noncompliant: exceptions caught by this statement should be re-raised or a more specific exception should be caught.
except SystemExit as e:
except BaseException as e:
... # Handle a more specific exception