In this chapter
We'll learn how throw stops a function and sends an exception up the call stack, how try and catch pick it up by type, how to catch several types, what finally guarantees, how an exception travels through functions until something catches it, and when to rethrow — plus the try-with-resources and try/else forms other languages have and PHP doesn't.
The Problem in Real Life
Mia wraps the whole booking page in try { ... } catch (Throwable $e) {} — an empty catch. The white page disappears. So does every error: now a missing booking, a typo in the template and a database outage all produce the same half-empty page, with nothing in the log.
Marcus reads the diff and shakes his head. "You didn't fix the error. You hid it."
Catch the problems you know how to handle, where you can handle them. Let the rest go up to someone who can.
Marcus
Catching Everything vs. Catching What You Can Handle
Catch by type
A catch block names the exceptions it handles; everything else keeps travelling.
finally always runs
Clean-up code in finally runs whether the try succeeded, failed or returned early.
Up the call stack
An uncaught exception leaves each function in turn until some caller catches it.
Throwing, Catching and Rethrowing
The syntax of failure: five keywords — throw, try, catch, finally and, again, throw — control what happens when something goes wrong. This chapter covers:
- throw: stopping a function with an exception.
- try and catch: handling exceptions by type.
- Several catch blocks: and catching several types in one block.
- finally: code that always runs.
- Propagation and rethrowing: how exceptions travel, and passing them on.
throw: throw new BookingNotFoundException("Booking 4812 does not exist"); creates an exception object and throws it. The current function stops immediately — the lines after throw don't run, and the function returns nothing. Since PHP 8.0, throw is also an expression, so it can sit where a value is expected: $booking = $repository->find($id) ?? throw new BookingNotFoundException(...), or inside an arrow function. That one line replaces an if that checks for null.
<?phpfinal class BookingNotFoundException extends RuntimeException {}function findBooking(int $id): ?array{return $id === 4811 ? ["customer" => "Tom Hart"] : null;}function loadBooking(int $id): array{return findBooking($id) ?? throw new BookingNotFoundException("Booking $id does not exist");}echo loadBooking(4811)["customer"], "\n"; // Tom Hartecho loadBooking(4812)["customer"], "\n"; // never printed// Tom Hart// Fatal error: Uncaught BookingNotFoundException: Booking 4812 does not exist in main.php:12
try and catch: code that may throw goes inside try { ... }. After it come one or more catch (SomeClass $e) { ... } blocks. If the code in try throws, PHP skips the rest of the try block and checks each catch from top to bottom; the first one whose class matches — the exception's own class, a parent class or an interface it implements — runs, and then the script continues after the whole try statement. If no catch matches, the exception keeps travelling up (below). Since PHP 8.0 the variable is optional: catch (BookingNotFoundException) when you don't need the object.
<?phpfinal class BookingNotFoundException extends RuntimeException {}function loadBooking(int $id): array{throw new BookingNotFoundException("Booking $id does not exist");}try {$booking = loadBooking(4812);echo "Hello ", $booking["customer"], "\n"; // skipped} catch (BookingNotFoundException $e) {http_response_code(404);echo "Sorry, we couldn't find that booking.\n";}echo "The page footer still prints.\n";// Sorry, we couldn't find that booking.// The page footer still prints.
Several catch blocks: different problems often need different reactions: a missing booking shows a 404 page, a database outage a "try again later" page. Write one catch per reaction, the most specific class first — a catch (Exception $e) at the top would match everything below it. When two types need the same reaction, catch both in one block with a vertical bar: catch (SlotTakenException | ShopClosedException $e). The table below shows which catch matches which exception.
| Thrown | catch (InvalidArgumentException) | catch (LogicException) | catch (Exception) | catch (Error) |
|---|---|---|---|---|
| InvalidArgumentException | Yes (itself) | Yes (parent) | Yes (grandparent) | No |
| DomainException | No | Yes (parent) | Yes | No |
| RuntimeException | No | No | Yes | No |
| TypeError | No | No | No | Yes |
<?phpfinal class SlotTakenException extends DomainException {}final class ShopClosedException extends DomainException {}final class DatabaseUnavailableException extends RuntimeException {}function book(string $slot): void{match ($slot) {"09:30" => throw new SlotTakenException("09:30 is already booked"),"Sunday" => throw new ShopClosedException("We're closed on Sundays"),"11:00" => throw new DatabaseUnavailableException("Database timeout"),default => print("Booked $slot\n"),};}foreach (["10:00", "09:30", "Sunday", "11:00"] as $slot) {try {book($slot);} catch (SlotTakenException | ShopClosedException $e) { // same reaction for bothecho "Please choose another time: ", $e->getMessage(), "\n";} catch (RuntimeException) { // no variable neededecho "Sorry, something went wrong on our side.\n";}}// Booked 10:00// Please choose another time: 09:30 is already booked// Please choose another time: We're closed on Sundays// Sorry, something went wrong on our side.
finally: a finally { ... } block after the catches runs always: when the try finished normally, when a catch handled an exception, when nothing caught it, and even when the try or catch executed return. That makes it the place for clean-up: unlocking a slot, closing a file, writing "request finished" to the log. One trap: a return inside finally replaces the return from try — and silently discards an exception on its way out. Never return from finally. Java's try-with-resources, C#'s using and Python's with close a resource automatically at the end of a block; PHP doesn't support that syntax. Use finally, or a destructor (Act 11), which PHP calls as soon as the object is no longer used.
<?phpfunction reserve(): string{try {echo "slot locked\n";return "reserved";} finally {echo "slot unlocked\n"; // runs even though try already returned}}function badIdea(): string{try {throw new RuntimeException("lost!");} finally {return "finally"; // swallows the exception: never do this}}echo reserve(), "\n";echo badIdea(), "\n";// slot locked// slot unlocked// reserved// finally
# Python — the file is closed at the end of the block, even on an exceptionwith open("bookings.csv") as f:rows = f.readlines()
Propagation: when nothing in the current function catches an exception, PHP leaves that function at once and passes the exception to the caller, at the line where it made the call. If the caller has a matching catch around that line, it runs; if not, the caller is left too, and so on, all the way up to the main script. Every function on the way stops in the middle — none of their remaining lines run, except finally blocks. The diagram below follows an exception from c() up to the main script. This is why a function deep inside the project doesn't need to know how errors are shown: it throws, and the code at the top decides.
An exception travels up the call stack
main script: try { a(); } catch (RuntimeException $e)
the only catch
a(): echo "a start"; b(); echo "a end";
"a end" never runs
b(): echo "b start"; c(); echo "b end";
"b end" never runs
c(): throw new RuntimeException("from c");
thrown here
c → b → a → main: caught
output: a start, b start, caught in main: from c
<?phpfunction a() { echo "a start\n"; b(); echo "a end\n"; }function b() { echo "b start\n"; c(); echo "b end\n"; }function c() { throw new RuntimeException("from c"); }try {a();} catch (RuntimeException $e) {echo "caught in main: ", $e->getMessage(), "\n";}// a start// b start// caught in main: from c
Rethrowing: sometimes code needs to do something with an exception — log it, roll back a half-finished change — but can't fully handle it. It catches, does its job, and throws again: throw $e; passes on the same object, with its original line and trace. Or it throws a new exception that wraps the old one (chapter 3). What it must never do is the empty catch from today's scene: catch (Throwable $e) {} swallows the problem, and the next person to debug it has nothing to go on.
<?phpfunction saveBooking(): void{echo "transaction started\n";try {throw new RuntimeException("Database timeout");} catch (RuntimeException $e) {echo "transaction rolled back\n"; // clean up what this function startedthrow $e; // and pass the same exception on}}try {saveBooking();} catch (RuntimeException $e) {echo "page: ", $e->getMessage(), " (thrown on line ", $e->getLine(), ")\n";}// transaction started// transaction rolled back// page: Database timeout (thrown on line 7)
What PHP doesn't have — try/else: Python has an else block that runs only when the try threw nothing; PHP doesn't support it. Put that code at the end of the try block (as long as its own exceptions should go to the same catches), or after the whole statement. The example below shows propagation, finally and rethrowing together.
Key Takeaway
throw stops the current function with an exception object; since PHP 8 it's an expression (?? throw new …). try marks code that may throw; the first catch whose class matches (including parents and interfaces) runs, then execution continues after the statement — order catches from specific to general, and use A | B for a shared reaction. finally always runs, so it's for clean-up; never return from it. Uncaught exceptions propagate to each caller in turn, skipping the rest of every function. Rethrow with throw $e; after logging or cleaning up, and never swallow exceptions with an empty catch. PHP lacks try-with-resources and try/else.
Why This Matters
Where you put try and catch decides what users see when things fail, and whether developers ever hear about it. Catching too little shows white pages; catching too much hides bugs for months.
finally is how real code keeps resources safe: database transactions, file locks and temporary files must be cleaned up whether the work succeeded or not. Act 15's file locks and Act 18's transactions both rely on it.
The booking page now catches BookingNotFoundException and shows a friendly 404; everything else still reaches the log. But BookBay's code throws RuntimeException for everything — a taken slot, a closed shop, a missing booking — so the page can't tell them apart without comparing message strings. And when the database fails, the log shows only "Could not load booking", without the real database error behind it. That's the next chapter: custom exceptions and chaining.
