Table of Contents

7. Error Handling — Exceptions, Types, and Failure Modes

Why this matters

Error handling is where PHP reveals its maturity.
Modern PHP expects:

AI often mixes old and new patterns, or generates code that hides errors instead of surfacing them.
This page gives us the mental model to recognize what “good” PHP error handling looks like.


1. PHP used to hide errors — modern PHP does not

Older PHP code often relied on:

Modern PHP is the opposite:

If AI generates code using old patterns, our mental model will flag it immediately.


2. Types are the first line of defense

PHP 7+ introduced real type safety:

function load(int $id): User { ... }

Types help you:

AI sometimes omits types or mixes nullable and non‑nullable types incorrectly.
Our understanding helps us correct that.


3. Exceptions are the modern failure mode

Instead of returning false or null, modern PHP throws exceptions:

throw new InvalidArgumentException("ID must be positive.");

And exceptions:

This is one of the clearest signs of modern PHP.


4. Use specific exceptions, not generic ones

Good PHP code uses domain‑specific exceptions:

class UserNotFound extends RuntimeException {}

And this allows for:

AI often uses Exception everywhere.
Our mental model helps us refine that.


5. Avoid suppressing errors

The @ operator hides problems:

$result = @file_get_contents($path);

This is almost always a mistake.
Modern PHP expects you to handle errors, not hide them.


6. Centralized error handling

Frameworks and modern apps often have:

This keeps the codebase clean, stable, and easy to reason about.


Summary

Modern PHP error handling is:

Once you internalize this, you can instantly see when AI‑generated code is living in the wrong era.