PHP Exceptions
An exception carries a failure to a handler. A useful handler either recovers meaningfully or adds context for a boundary that can decide how to respond.
How it works
Throwable covers both Exception and Error hierarchies. Catch a specific type when only that failure is expected, and avoid turning every programming error into a plausible success value. finally handles cleanup even when the protected operation fails, but a return or new exception in finally can replace an earlier result/failure. Distinguish a missing optional value from an operation that genuinely cannot complete.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l exceptions.php
php exceptions.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
function requirePositive(int $count): int {
if ($count <= 0) throw new InvalidArgumentException("Positive count required");
return $count;
}
try { requirePositive(0); }
catch (InvalidArgumentException $error) { echo "Input rejected\n"; }
finally { echo "Boundary finished\n"; }
Expected result
Input rejected
Boundary finishedThe handler recognises the specific input-contract failure. The finally block demonstrates a boundary action without changing the return or throwing a replacement exception. A web entry point would map the failure into a suitable controlled response and a test would verify that no state-changing operation ran after rejection.
Check the official PHP manual for detailed version and API contracts.