How to use exceptions in PHP
Sometimes errors are unavoidable.
Something completely unpredictable happens.
But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or try a workaround.
We do so using exceptions.
Exceptions are used to make us, developers, aware of a problem.
We wrap some code that can potentially raise an exception into a try
block, and we have a catch
block right after that. That catch block will be executed if there’s an exception in the try block:
try {
//do something
} catch (Throwable $e) {
//we can do something here if an exception happens
}
Notice that we have an Exception
object $e
being passed to the catch
block, and we can inspect that object to get more information about the exception, like this:
try {
//do something
} catch (Throwable $e) {
echo $e->getMessage();
}
Let’s do an example.
For example by mistake I divide a number by zero:
echo 1 / 0;
This will trigger a fatal error and the program is halted on that line:
Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:
try {
echo 1 / 0;
} catch (Throwable $e) {
echo $e->getMessage();
}
Of course this is a simple example but you can see the benefit: I can intercept the issue.
Each exception has a different class. For example we can catch this as DivisionByZeroError
and this lets me filter the possible problems and handle them differently.
I can have a catch-all for any throwable error at the end, like this:
try {
echo 1 / 0;
} catch (DivisionByZeroError $e) {
echo 'Ooops I divided by zero!';
} catch (Throwable $e) {
echo $e->getMessage();
}
And I can also append a finally {}
block at the end of this try/catch structure to execute some code after the code is either executed successfully without problems, or there was a catch:
try {
echo 1 / 0;
} catch (DivisionByZeroError $e) {
echo 'Ooops I divided by zero!';
} catch (Throwable $e) {
echo $e->getMessage();
} finally {
echo ' ...done!';
}
You can use the built-in exceptions provided by PHP but you can also create your own exceptions.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025