PHP Exceptions and finally
Lesson 27 of 43 in the PHP 8 learning path.
How do I throw and catch a domain exception?
A domain exception is your own class, extending RuntimeException, for a rule the program can name. EnrollmentException means the seat request was refused. throw leaves the try block. catch runs only when the thrown object is of that type, so a TypeError still surfaces. finally runs on the way out, whether the function returns a remaining count or throws.
Close files and other resources in finally. Do not catch the base Exception at the bottom of a small function and return null. The caller needs to know the request failed. Do not use exceptions for an ordinary empty search. A missing row can be an empty list. An impossible seat count is the exceptional case.
Syntax & Parameters
try { enroll($seats, $requested); } catch (EnrollmentException $exception) { }
Example
<?php
declare(strict_types=1);
final class EnrollmentException extends RuntimeException
{
}
function enroll(int $seats, int $requested): int
{
$handle = fopen('php://temp', 'w+b');
if ($handle === false) {
throw new EnrollmentException('Could not open the enrollment log.');
}
try {
if ($requested < 1) {
throw new EnrollmentException('Request at least one seat.');
}
if ($requested > $seats) {
throw new EnrollmentException('Not enough seats remain.');
}
$written = fwrite($handle, 'enrolled ' . $requested);
if ($written === false) {
throw new EnrollmentException('Could not write the enrollment log.');
}
return $seats - $requested;
} finally {
fclose($handle);
echo "log closed\n";
}
}
try {
echo 'left ' . enroll(5, 2) . "\n";
echo 'left ' . enroll(1, 4) . "\n";
} catch (EnrollmentException $exception) {
echo 'caught: ' . $exception->getMessage() . "\n";
}
Expected Output
log closed left 3 log closed caught: Not enough seats remain.
Line-by-Line Walkthrough
- EnrollmentException extends RuntimeException so a refused enrollment is a named domain error.
- fopen opens an in-memory log. A false handle throws before try, because there is no resource to close yet.
- A request below 1 throws. The caller did not ask for a real seat.
- A request above the remaining seats throws Not enough seats remain.
- The success path writes the log, checks fwrite, and returns the seats that are left.
- finally closes the handle and prints log closed. It runs when the function returns and when it throws.
- That print happens before the caller receives the return value, so log closed appears before left 3.
- The second call throws. finally still closes the handle, and the exception then leaves the function.
- The caller catches only EnrollmentException and prints the message.
- A different throwable would skip this catch, so a bug in the function is not reported as a refused enrollment.
Common Pitfalls & Security
An exception is for a broken rule, not for ordinary control flow. Catch the type you can handle, and let the rest reach the error log.
- catch (Exception) or catch (Throwable) around a small step hides programming errors and turns them into a generic failure.
- A return inside finally replaces the pending return value and can discard the exception you meant to throw.
- Opening the resource inside the try and closing it in finally is wrong when fopen failed and the handle does not exist.
- Throwing a string, or using a numeric error code with no class, gives the caller nothing specific to catch.
- Do not put a password or a full request body in the exception message. Messages are often logged and sometimes shown.
- A caught enrollment error is not a successful write. Do not decrement seats after the catch runs.
Best Practices & Modern Standards
Create one exception class per domain failure that callers handle differently. Put the user-facing sentence in the message, and keep internal identifiers out of it. Typehint the catch to that class.
Use finally for cleanup that must happen on both success and failure. Do not use finally to decide the business result. Test the refusal path and the success path, including the order: cleanup runs before the caller sees the return or the catch.
Real-World Use
A request for 2 seats out of 5 returns 3 left and still closes the log. A request for 4 seats when 1 remains throws EnrollmentException. The handle is closed in finally, and the page prints the caught message instead of saving a partial enrollment.
Frequently Asked Questions
Which type should I catch?
Catch the domain type you can recover from, such as EnrollmentException. Leave TypeError and other bugs uncaught so they are fixed instead of shown as a full class.
Does finally run on a return?
Yes. finally runs before the function actually returns to the caller, and it also runs when an exception is leaving the try block.
Should an empty search throw?
No. An empty result is a normal list. Throw when a rule is broken, such as a seat request that cannot be honored.
Can finally swallow the exception?
A return or a new throw inside finally replaces what the try block was about to do. Close the resource in finally and let the original exception continue.