SystemExit is raised when sys.exit() is called. This exception is expected to propagate up until the application stops. It is ok to catch it when a clean-up is necessary but it should be raised again immediately.

A bare except: statement, i.e. an except without any exception class, is equivalent to except BaseException. Both statements will catch every exception, including SystemExit. It is recommended to catch instead a specific exception. If it is not possible, the exception should be raised again.

Note that it is also a good idea to reraise the KeyboardInterrupt exception.

This rule raises an issue when a bare except:, an except BaseException or an except SystemExit don't reraise the exception caught.

Noncompliant Code Example

try:
    open("foo.txt", "r")
except SystemExit:  # Noncompliant
    pass
except KeyboardInterrupt:  # No issue raised but be careful when you do this
    pass

try:
    open("bar.txt", "r")
except BaseException:  # Noncompliant
    pass
except:  # Noncompliant
    pass

Compliant Solution

try:
    open("foo.txt", "r")
except SystemExit:
    # clean-up
    raise
except KeyboardInterrupt:
    # clean-up
    raise

try:
    open("bar.txt", "r")
except BaseException as e:
    # clean-up
    raise e
except: # Noncompliant
    # clean-up
    raise

# or use a more specific exception

try:
    open("bar.txt", "r")
except FileNotFoundError:
    # process the exception

See