Exceptions and error handling
An exception in modern PHP is an object that represents the data for a particular error condition. Exceptions are not generally created with create
but instead they are thrown, as in they are created and unleashed with one magic keyword: throw
.
If you don't know about exceptions, it's time to hit the docs:
PHP: Exceptions - Manual
https://www.php.net/manual/en/language.exceptions.php
Once an exception is thrown, then it must be caught or it will become a Fatal Error
. I always imagine it a bit like setting off the timer on a bomb. The bomb gets passed from handler to handler until it either hits someone who has the right tools to disable it, or we run out of layers
that can possibly handle it and it goes off… boom.
We catch exceptions with the catch
keyword. The catch
keyword is always used with a type hint for what kind of exceptions it will catch. This can be quite specific, or can be totally general by hinting for Throwable...