Skip to content

Do Not Use Bare Except

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

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

Section titled “Sourcery suggestion id: do-not-use-bare-except”

Use except: Exception rather than bare except

try:
some_important_code()
except:
exception_handling_code()
try:
some_important_code()
except Exception:
exception_handling_code()

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.