{
    "slug": "py_error_handling",
    "term": "Python Error Handling",
    "category": "python",
    "difficulty": "intermediate",
    "short": "Python uses try/except/else/finally blocks and a rich exception hierarchy — good error handling is specific, informative, and never silently swallows exceptions.",
    "long": "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.",
    "aliases": [
        "try/except",
        "exception handling",
        "Python exceptions"
    ],
    "tags": [
        "python",
        "error-handling",
        "best-practices"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_context_managers",
        "py_logging",
        "py_type_hints"
    ],
    "prerequisites": [
        "py_type_hints",
        "fail_fast",
        "exception_handling"
    ],
    "refs": [
        "https://docs.python.org/3/tutorial/errors.html"
    ],
    "bad_code": "# Silent exception swallowing — hides all errors:\ndef get_user(user_id):\n    try:\n        return db.fetch(user_id)\n    except:  # Catches EVERYTHING including KeyboardInterrupt\n        pass  # Returns None silently — caller has no idea what went wrong",
    "good_code": "# Specific exception handling with context:\nclass UserNotFoundError(ValueError):\n    def __init__(self, user_id):\n        super().__init__(f'User {user_id} not found')\n        self.user_id = user_id\n\ndef get_user(user_id: int) -> User:\n    try:\n        return db.fetch(user_id)\n    except DatabaseConnectionError as e:\n        raise RuntimeError('Database unavailable') from e  # Preserve chain\n    except RecordNotFoundError:\n        raise UserNotFoundError(user_id)  # Domain-specific exception\n    # No finally needed here — let other exceptions propagate",
    "quick_fix": "Catch specific exceptions, never bare except: — bare except catches SystemExit and KeyboardInterrupt preventing clean shutdown; use except Exception as e: at minimum",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_error_handling",
        "html_url": "https://codeclaritylab.com/glossary/py_error_handling",
        "json_url": "https://codeclaritylab.com/glossary/py_error_handling.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Python Error Handling](https://codeclaritylab.com/glossary/py_error_handling) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_error_handling"
            }
        }
    }
}