{
    "slug": "exception_handling",
    "term": "Exception Handling (try/catch/finally)",
    "category": "php",
    "difficulty": "intermediate",
    "short": "PHP's structured error handling mechanism that separates error-path code from the happy path and ensures resource cleanup.",
    "long": "PHP exceptions should be used for exceptional, unrecoverable conditions — not for flow control. Catch specific exception types rather than the base Exception or Throwable, use finally blocks for guaranteed resource cleanup (closing files, releasing locks), and never swallow exceptions silently in an empty catch block. PHP 8.0 introduced non-capturing catches (catch (ExceptionType)) when the exception object itself isn't needed. Custom exception hierarchies help callers handle different error categories appropriately.",
    "aliases": [
        "PHP try catch",
        "exception hierarchy PHP",
        "Throwable interface"
    ],
    "tags": [
        "php",
        "error-handling",
        "quality"
    ],
    "misconception": "catch (Exception $e) catches all PHP errors. PHP 7+ separates exceptions (Exception) from engine errors (Error) — both extend Throwable. Catching Exception misses TypeError, ArithmeticError, and ParseError. Use catch (Throwable $e) only when you truly need to catch everything.",
    "why_it_matters": "Exceptions provide a structured, unforgeable signal that something went wrong — they cannot be accidentally ignored the way return codes can. Proper exception hierarchies let callers handle errors at the right level of abstraction.",
    "common_mistakes": [
        "Catching \\Exception or \\Throwable everywhere and swallowing it — silent failure is worse than a crash.",
        "Using exceptions for normal control flow (throwing to exit a loop) — exceptions are for exceptional situations.",
        "Not creating domain-specific exception classes — catching RuntimeException tells callers nothing useful.",
        "Logging the exception and rethrowing without passing the original as $previous — you lose the stack trace chain."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "error_handling",
        "fail_fast"
    ],
    "prerequisites": [
        "named_exceptions",
        "error_handling",
        "try_catch_patterns"
    ],
    "refs": [
        "https://www.php.net/manual/en/language.exceptions.php"
    ],
    "bad_code": "// Catching the base Exception hides bugs; empty catch silences everything\ntry {\n    $this->processOrder($order);\n} catch (\\Exception $e) {\n    // do nothing — you'll never know what went wrong\n}",
    "good_code": "try {\n    $this->processOrder($order);\n} catch (InsufficientStockException $e) {\n    return response()->json(['error' => 'Item out of stock'], 409);\n} catch (PaymentDeclinedException $e) {\n    $this->logger->warning('Payment declined', ['order' => $order->id]);\n    return response()->json(['error' => 'Payment failed'], 402);\n} catch (\\Throwable $e) {\n    $this->logger->error('Unexpected error', ['exception' => $e]);\n    throw $e; // rethrow — let global handler deal with it\n}",
    "quick_fix": "Catch specific exception types not \\Exception or \\Throwable at every level; let domain exceptions propagate, catch only what you can handle",
    "severity": "medium",
    "effort": "medium",
    "created": "2026-03-13",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/exception_handling",
        "html_url": "https://codeclaritylab.com/glossary/exception_handling",
        "json_url": "https://codeclaritylab.com/glossary/exception_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": "[Exception Handling (try/catch/finally)](https://codeclaritylab.com/glossary/exception_handling) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/exception_handling"
            }
        }
    }
}