← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Python Error Handling

Python Python 2.0+ Intermediate
debt(d3/e2/b5/t5)
d3 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'default linter catches the common case' (d3) — pylint, ruff (E722), and flake8 flag bare except: directly; broad Exception catching also flagged by default rules.

e2 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch' (e1), nudged to e2 — per quick_fix, replacing 'except:' with 'except SpecificError as e:' plus logging is typically a one- or two-line change per occurrence, though multiple sites may need updating.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5) — error handling style applies across web and CLI contexts (per applies_to); sloppy patterns silently swallow bugs throughout the codebase, creating ongoing debugging tax across many work streams.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap most devs eventually learn' (t5) — per misconception, the belief that broad except is safe is canonical; bare except swallowing KeyboardInterrupt/SystemExit is a documented gotcha that competent devs guess wrong about initially.

About DEBT scoring →

Also Known As

try/except exception handling Python exceptions

TL;DR

Python uses try/except/else/finally blocks and a rich exception hierarchy — good error handling is specific, informative, and never silently swallows exceptions.

Explanation

Python exceptions are objects in a hierarchy (BaseException > Exception > specific types). Best practices: catch the most specific exception possible, not bare except or except Exception. The else clause runs when no exception was raised — useful for code that should only run on success. finally always runs — use it for cleanup. Custom exceptions should inherit from Exception, not BaseException. Use raise from to preserve exception chains.

Common Misconception

Broad exception catching is safe — catching all exceptions hides bugs, makes debugging impossible, and swallows keyboard interrupts and memory errors.

Why It Matters

Silent exception swallowing is one of the most common sources of mysterious Python bugs — a function that silently returns None when it should raise tells the caller nothing went wrong.

Common Mistakes

  • Bare except: clause — catches everything including SystemExit and KeyboardInterrupt; always specify the exception type.
  • Using pass in an except block — silently swallows the error with no logging or handling.
  • Not using raise from to preserve the original exception context: raise NewException(...) from original_exc.
  • Catching broad Exception when a specific type is known — makes error messages less informative and hides unrelated bugs.

Code Examples

✗ Vulnerable
# Silent exception swallowing — hides all errors:
def get_user(user_id):
    try:
        return db.fetch(user_id)
    except:  # Catches EVERYTHING including KeyboardInterrupt
        pass  # Returns None silently — caller has no idea what went wrong
✓ Fixed
# Specific exception handling with context:
class UserNotFoundError(ValueError):
    def __init__(self, user_id):
        super().__init__(f'User {user_id} not found')
        self.user_id = user_id

def get_user(user_id: int) -> User:
    try:
        return db.fetch(user_id)
    except DatabaseConnectionError as e:
        raise RuntimeError('Database unavailable') from e  # Preserve chain
    except RecordNotFoundError:
        raise UserNotFoundError(user_id)  # Domain-specific exception
    # No finally needed here — let other exceptions propagate

Added 15 Mar 2026
Edited 22 Mar 2026
Views 55
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 1 ping S 0 pings M 1 ping T 1 ping W 1 ping T 3 pings F 3 pings S 2 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 2 pings S 0 pings M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Scrapy 12 Amazonbot 9 Perplexity 6 Ahrefs 5 ChatGPT 3 Unknown AI 3 Google 3 Claude 2 Meta AI 1 PetalBot 1
crawler 42 crawler_json 3
DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Low
⚡ Quick Fix
Catch specific exceptions, never bare except: — bare except catches SystemExit and KeyboardInterrupt preventing clean shutdown; use except Exception as e: at minimum
📦 Applies To
python 2.0 web cli
🔗 Prerequisites
🔍 Detection Hints
bare except: without exception type; catching Exception silently; no logging in except block; using exceptions for control flow
Auto-detectable: ✓ Yes pylint ruff flake8 mypy
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Medium Context: Function Tests: Update
CWE-390 CWE-755


✓ schema.org compliant