Programming Search⌘K

Featurecore

Broad except clauses

Also called bare except, except Exception, catch-all exception handler, try-except-pass, swallowed exception, E722, BLE001, S110, W0702, W0718, broad-exception-caught.

A bare except or except Exception catches more than the error you expect, so it hides typos and real bugs. Catch the specific exception, and log and re-raise in a catch-all handler.

Language
Python

Synopsis

This code runs but gives a wrong answer on purpose.

def parse_port(text):
    try:
        return int(txt)
    except:
        return 8080


print(parse_port("9000"))
Output
8080

The function has a typo, txt, so every call raises NameError. The bare except: catches that error too, and the function returns the default for every input.

Semantics

r1. PEP 8 says: "When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause".1 Example: specific.

r2. A bare except: catches everything. "A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:)."1

r3. The hierarchy keeps the exit signals out of Exception. Exception is the base of "All built-in, non-system-exiting exceptions".2 KeyboardInterrupt "inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting."2 SystemExit "inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception."2 Example: exit-swallowed.

r4. except Exception: is still broad. It catches NameError, AttributeError and TypeError, which are usually bugs in the code, not conditions to handle. Example: typo-hidden.

r5. An empty handler is the worst case. Ruff explains: "The try-except-pass pattern suppresses all exceptions. Suppressing exceptions may hide errors that could otherwise reveal unexpected behavior, security vulnerabilities, or malicious activity. Instead, consider logging the exception."3

r6. A catch-all handler has a place at the top of a program or a worker loop, where one failure must not stop the others. There, record the error with its traceback. logging.exception "Logs a message with level ERROR on the root logger" and "Exception info is added to the logging message. This function should only be called from an exception handler."4 Then re-raise with a bare raise if the caller must know. Example: log-and-raise.

r7. The linters:

  • Ruff E722 "Checks for bare except catches in try-except statements."5 Its reason: "A bare except catches BaseException which includes KeyboardInterrupt, SystemExit, Exception, and others."5
  • Ruff BLE001 "Checks for except clauses that catch all exceptions. This includes except BaseException and except Exception."6
  • Ruff S110 reports try, except and pass (rule r5).3
  • Pylint W0702 bare-except has the message "No exception type(s) specified".7 Pylint W0718 broad-exception-caught has the message "Catching too general exception %s".8

Examples

def parse_port(text):
    try:
        return int(text)
    except ValueError:
        return 8080


print(parse_port("9000"))
print(parse_port("http"))
Output
9000
8080

The handler names ValueError, the error that int raises for bad text (rule r1). A typo in the body now raises NameError and shows the bug.

import logging

records = []


class Keep(logging.Handler):
    def emit(self, record):
        records.append(record)


logging.getLogger().addHandler(Keep())


def run_job(job):
    return 10 // job


for job in [5, 0]:
    try:
        print(run_job(job))
    except Exception:
        logging.exception("job %r failed", job)

for r in records:
    print(r.levelname, r.getMessage(), r.exc_info[0].__name__)
Output
2
ERROR job 0 failed ZeroDivisionError

The loop goes on after a failed job, and the log record holds the exception and its traceback, so the error is not lost (rule r6).

Versions

The rules are the same in all Python 3 versions.

Pitfalls

This code runs but gives a wrong answer on purpose.

import sys


def main():
    try:
        sys.exit(2)
    except:
        print("error ignored")
    return "still running"


print(main())
Output
error ignored
still running

The bare except: caught SystemExit, so the program did not stop (rule r3). With except Exception:, the exit goes through.

This code raises KeyError, on purpose.

config = {"host": "localhost"}

try:
    port = config["port"]
except KeyError:
    print("no port in the config")
    raise

A bare raise in a handler raises the same exception again, with its traceback. The handler adds a message, and the caller still sees the error (rule r6).

Comparison

In Python, a handler that is too broad catches errors that are bugs in the code, such as NameError, because those are exceptions too. So the size of the handler matters as much as its class: keep the try block small, so it holds only the call that can fail. For the hierarchy, see The exception hierarchy. For the general topic, see Exception.

References

  1. PEP 8, Style Guide for Python Code, Programming Recommendations
  2. Built-in Exceptions, Python 3.15 documentation, Base classes; SystemExit; KeyboardInterrupt
  3. try-except-pass (S110), Ruff documentation, Why is this bad?
  4. logging, Logging facility for Python, Python 3.15 documentation, logging.exception()
  5. bare-except (E722), Ruff documentation, What it does; Why is this bad?
  6. blind-except (BLE001), Ruff documentation, What it does
  7. bare-except / W0702, Pylint documentation, Message
  8. broad-exception-caught / W0718, Pylint documentation, Message

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source