Exceptions
An exception stops the normal path of a program and carries a reason to code that can handle it. In PHP the throw statement builds that object, and the try statement decides where it is caught.
Throw
Use throw when a function cannot keep its contract.
Throwing stops the current path at once and carries an object with the reason.
Since PHP 8.0 throw is also an expression, so it fits inside
null coalescing and arrow functions.
<?php function findUser(int $id): array { if ($id <= 0) { throw new InvalidArgumentException("Bad id"); } return ["id" => $id]; } $user = findUser(7); echo $user["id"], PHP_EOL; try { $port = $_ENV["PORT"] ?? throw new RuntimeException("PORT is not set"); } catch (RuntimeException $e) { echo $e->getMessage(), PHP_EOL; }
php throw.php
7
PORT is not set
The valid id returns a user, and the missing environment variable throws from inside the expression. The catch turns that second failure into one readable line instead of a fatal error.
Catch by type
Wrap risky calls in try and handle each failure with a matching
catch block. The first block with a compatible type wins.
Put specific types first and general types last, otherwise the general block hides the rest.
<?php function findUser(int $id): array { if ($id <= 0) { throw new InvalidArgumentException("Bad id"); } return ["id" => $id]; } try { $user = findUser(-5); echo $user["id"], PHP_EOL; } catch (InvalidArgumentException $e) { echo "Fix the id", PHP_EOL; } catch (Throwable $e) { echo "Something failed", PHP_EOL; }
php catch.php
Fix the id
The negative id throws before the user is built, so the first catch takes it and the second one never runs. A different failure of the same call would fall through to the general block.
finally always runs
A finally block runs whether the code succeeds, throws, or returns early.
It is the right place to close files, unlock resources, and stop timers.
Keep it small and exception free so it never masks the original error.
<?php function work(): string { $lock = fopen("lock.txt", "w"); try { return "work"; } finally { fclose($lock); echo "lock closed", PHP_EOL; } } echo work(), PHP_EOL; try { throw new RuntimeException("broken"); } catch (Throwable $e) { echo "failed: ", $e->getMessage(), PHP_EOL; } finally { echo "finally after catch", PHP_EOL; }
php finally.php
lock closed
work
failed: broken
finally after catch
The return in the inner try still runs its finally first, which is why the lock line comes before the returned value. The outer finally runs after the catch, so the cleanup happens on the failing path too.
Your own exception class
Create a domain exception by extending Exception or
RuntimeException. Callers can then catch your failure without
catching every unrelated error.
Remember the split in the engine: Exception is for logic failures and
Error is for engine failures. Catch Throwable
when you must handle both branches at once.
<?php class UserNotFound extends RuntimeException { } try { throw new UserNotFound("Ada is missing"); } catch (UserNotFound $e) { echo $e->getMessage(), PHP_EOL; }
php custom.php
Ada is missing
The catch names the small class, so it would not take a database failure that also extends RuntimeException. The message travels with the object and arrives unchanged at the handler.
Exercises
- Call findUser(0) and add a catch that prints the message of the exception.
- Swap the two catches in catch.php and run it again. Which line appears?
- Make the inner try in finally.php throw instead of return. Which lines still print?
- Add a code argument to UserNotFound and read it in the catch.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
throwdo?Answer
It stops the current path and passes an exception object to the nearest handler
The statement leaves the current function at once, and the exception travels to the first matching catch.
-
Which block runs whether the try succeeds, throws or returns early?
Answer
finallyPHP runs the finally block on every way out of the try, including a return.
-
Which type do
ExceptionandErrorboth descend from?Answer
ThrowableThrowable is the common interface, so one catch of it takes both branches.
-
Why does the specific catch come first?
Answer
The first compatible block wins, so a general one would hide the rest
A catch of Throwable matches every exception, so any later block becomes unreachable.
-
What does this program print?
<?php function findUser(int $id): array { if ($id <= 0) { throw new InvalidArgumentException("Bad id"); } return ["id" => $id]; } $user = findUser(7); echo $user["id"];Answer
7
A positive id passes the check and is returned in the array, so the echo prints it.
-
What does this program print?
<?php function findUser(int $id): array { if ($id <= 0) { throw new InvalidArgumentException("Bad id"); } return ["id" => $id]; } try { $user = findUser(-5); echo $user["id"]; } catch (InvalidArgumentException $e) { echo "Fix the id"; } catch (Throwable $e) { echo "Something failed"; }Answer
Fix the id
The negative id throws InvalidArgumentException, which the first catch takes.
-
What does this program print?
<?php function work(): string { try { return "work"; } finally { echo "lock closed", PHP_EOL; } } echo work();Answer
lock closed / work
The finally block runs before the value leaves the function, so its line comes first.
-
What does this program print?
<?php class UserNotFound extends RuntimeException { } try { throw new UserNotFound("Ada is missing"); } catch (UserNotFound $e) { echo $e->getMessage(); }Answer
Ada is missing
The subclass inherits the constructor and the message, and the catch reads it back.
-
What does this program print?
<?php try { $port = $_ENV["PORT"] ?? throw new RuntimeException("PORT is not set"); } catch (RuntimeException $e) { echo $e->getMessage(); }Answer
PORT is not set
The missing key takes the right side of the null coalescing, and since PHP 8.0 throw is an expression there.
-
What does this program print?
<?php try { throw new InvalidArgumentException("Bad id"); } catch (Throwable $e) { echo "Something failed"; } catch (InvalidArgumentException $e) { echo "Fix the id"; }Answer
Something failed
Throwable matches first and takes the exception, so the specific block below it never runs.
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