Skip to content

Do Not Use Bare Except

Sourcery suggestion id: do-not-use-bare-except

Description

Use except: Exception rather than bare except

Before

try:
    some_important_code()
except:
    exception_handling_code()

After

try:
    some_important_code()
except Exception:
    exception_handling_code()

Explanation

PEP 8 recommends that we should avoid catching exceptions using a bare except clause.

The problem with these is that they catch SystemExit and KeyboardInterrupt exceptions, which makes it harder to interrupt a program using CTRL+C, and can also disguise other problems.

The PEP recommends catching Exception, which will catch all program errors, so that is what Sourcery suggests. Note that this suggestion does not trigger if the exception handler ends by raising the original exception.