Exceptions advanced
An exception in PHP carries a message, a code and an optional earlier one, and the four blocks below use all three parts: the tree of throwable types, a named class for one failure, a chain that keeps the cause, and a cleanup block that always runs.
Throwable tree
Throwable sits at the top of the tree, with Error and Exception below it. Most daily code throws and catches Exception types.
Catch narrow types first and broad types last. Let most Errors surface during development so real bugs stay loud.
<?php try { throw new RuntimeException("boom"); } catch (LogicException $e) { echo "narrow: ", $e->getMessage(), PHP_EOL; } catch (RuntimeException $e) { echo "broad: ", $e->getMessage(), PHP_EOL; } echo "after", PHP_EOL;
php hierarchy.php
broad: boom
after
The narrow arm was tested first and did not match, because a runtime error is not a logic error. The second arm caught it, and the line after the block proves that the program kept going.
Custom classes
Small exception classes name each failure. A reader sees NotFound at once instead of decoding a plain message.
Extend a fitting base like RuntimeException and add no extra code at first. The name alone already helps logs and catch blocks.
<?php class NotFound extends RuntimeException { } try { throw new NotFound("page gone"); } catch (NotFound $e) { echo get_class($e), ": ", $e->getMessage(), PHP_EOL; } echo $e instanceof RuntimeException ? "is a RuntimeException" : "not", PHP_EOL;
php custom.php
NotFound: page gone
is a RuntimeException
The catch named the small class, and the parent check shows that a broader catch would have taken the same object.
Previous chaining
Wrap a low level error in a clearer one, but keep the first error as previous. The full chain stays open for logs and debug screens.
Pass the caught error as the third argument when you throw the new one. getPrevious reads the chain back later.
<?php try { try { throw new RuntimeException("db down", 7); } catch (RuntimeException $e) { throw new RuntimeException("login failed", 0, $e); } } catch (RuntimeException $e) { echo $e->getMessage(), PHP_EOL; $prev = $e->getPrevious(); echo $prev->getMessage(), PHP_EOL; echo $prev->getCode(), PHP_EOL; }
php previous.php
login failed
db down
7
The outer message is the one the user sees, and the chain still holds the database error with the code that came with it.
Finally patterns
The finally block runs with or without an error. It is the home for cleanup that must always happen.
Close handles and release locks there. Every path then cleans up the same way, and resources never leak past the call.
<?php $f = fopen("php://memory", "r+"); fwrite($f, "hello"); rewind($f); try { $line = fgets($f); echo $line, PHP_EOL; throw new RuntimeException("inside"); } catch (RuntimeException $e) { echo "caught: ", $e->getMessage(), PHP_EOL; } finally { fclose($f); echo "closed", PHP_EOL; } echo "done", PHP_EOL;
php finally.php
hello
caught: inside
closed
done
The handle was closed on the error path, and the line after the block shows that the catch ended the trouble instead of the program.
Exercises
- Throw a LogicException and catch it with a narrow arm before a broad one.
- Write two custom exceptions and catch each one separately.
- Chain three exceptions and print every message from the last to the first.
- Use finally to close a handle when the block returns early.
- Explain why catching Throwable everywhere hides real bugs.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which two types sit directly below Throwable?
Answer
Error and Exception
Throwable is the root interface, and Error and Exception are the two families under it.
-
In which order should catch blocks be written?
Answer
Narrow types first, broad types last
A broad arm catches everything below it, so a narrow arm after it would never run.
-
How is an earlier exception attached to a new one?
Answer
As the third argument of the constructor
The constructor is (message, code, previous), so the cause goes in the third slot.
-
When does a finally block run?
Answer
On both paths, including an early return
The cleanup block belongs to the whole try statement, so every exit path passes through it.
-
What does this program print?
<?php try { throw new RuntimeException("boom"); } catch (LogicException $e) { echo "narrow"; } catch (RuntimeException $e) { echo "broad: ", $e->getMessage(); }Answer
broad: boom
A RuntimeException is not a LogicException, so the second arm takes it and prints its message.
-
What does this program print?
<?php class NotFound extends RuntimeException { } try { throw new NotFound("page gone"); } catch (RuntimeException $e) { echo get_class($e); }Answer
NotFound
The object keeps its own class, and the broader catch still receives the NotFound instance.
-
What does this program print?
<?php try { try { throw new RuntimeException("db down"); } catch (RuntimeException $e) { throw new RuntimeException("login failed", 0, $e); } } catch (RuntimeException $e) { echo $e->getMessage(), " ", $e->getPrevious()->getMessage(); }Answer
login failed db down
The outer exception holds the new message, and getPrevious() reaches the original one.
-
What does this program print?
<?php try { try { throw new RuntimeException("inner", 7); } catch (RuntimeException $e) { throw new RuntimeException("outer", 0, $e); } } catch (RuntimeException $e) { echo $e->getPrevious()->getCode(); }Answer
7
The code travels with the exception it was created with, which is 7 on the inner one.
-
What does this program print?
<?php function run(): string { try { return "try"; } finally { echo "cleanup "; } } echo run();Answer
cleanup try
The finally block runs before the value leaves the function, so its output comes first.
-
Why is catching
Throwableeverywhere a bad habit?Answer
It also swallows programming errors that should stop the program
Undefined methods and type mistakes are Errors, and hiding them turns a loud bug into a quiet one.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev