Errors, exceptions and types
PHP 8 turned many old warnings into proper exceptions, and added a strong type system. Used together they make bugs loud and early: a wrong type or a failed operation stops right where it happened, with a clear message, instead of producing a wrong page three steps later. This lesson covers both.
Exceptions: try, catch, finally
throw new SomeException("message")raises an exception.catch (A | B $e)handles one or several types; the first matchingcatchwins.finallyalways runs, whether or not an exception happened, which makes it the place to clean up.
The hierarchy: Exception and Error
Everything you can throw implements Throwable, which has two families:
Errormeans a programming bug: calling an undefined function, a type error, division by zero. You generally fix these rather than catch them.Exceptionmeans something that can legitimately go wrong at run time: invalid input, a missing file, a failed database query. These are what you catch.catch (Throwable $t)catches both, which is right only at the very top of an app (to log and show an error page).
Your own exception classes
A common base class (ShopException) lets callers catch every error from your code at once, while specific classes carry extra data.
Wrapping exceptions
When you catch a low-level exception and throw a more meaningful one, pass the original as previous, so nothing is lost:
Uncaught exceptions
If nothing catches an exception, PHP prints a fatal error with the stack trace and stops:
Note ?? throw …: since PHP 8, throw is an expression, so it can be used after ?? and in arrow functions.
In production, set display_errors=Off (so visitors never see stack traces), log_errors=On, and register a top-level handler that logs the error and shows a friendly page. Frameworks like Laravel do all of this for you.
Types in depth
Declaring types everywhere, with strict_types, turns many bugs into immediate, precise errors:
| Type feature | Example |
|---|---|
| Scalar types | int, float, string, bool |
| Nullable | ?string (string or null) |
| Union | int|float |
| Intersection | Countable&Traversable (must be both) |
mixed, void, never, static, self |
Special types |
| Typed properties | private array $lines = []; |
readonly |
Set once, then fixed |
Static analysis
Types also let tools check your code without running it. PHPStan and Psalm read your types (and docblocks like @var list<…>) and find bugs such as calling a method on something that might be null. Install with Composer and run vendor/bin/phpstan analyse src --level=6. Most professional PHP projects run one in CI.
Warnings and notices
Some problems still produce warnings instead of exceptions, and the script continues:
Treat warnings as bugs. In development, use an error handler (or your framework's) that turns them into exceptions, so they can't be ignored:
Practice
- Write
divide(float $a, float $b): floatthat throwsInvalidArgumentExceptionfor division by zero, and call it insidetry/catch. - Create
ValidationExceptionthat carries an array of field errors, and print them all when it's caught. - Add
declare(strict_types=1)to a script of yours, and fix everyTypeErrorit reveals. - Use
?? throwto require a$_GET-style array key.
1.When does a finally block run?
2.What's the difference between Error and Exception in PHP 8?
3.Why pass previous: $e when throwing a new exception?
4.What does ?? throw new Exception(...) do?