try, catch, and finallyA PHP exception is an object describing an unexpected error—such as a missing file, invalid API payload, or failed database query—that interrupts normal execution until caught by a handler. Exceptions separate error recovery from happy-path business logic so your functions stay clean.
try, catch, and finallyWrap risky operations inside a try block and handle specific exception types in catch blocks ordered from most specific to most general. Code inside finally always runs afterward, whether an exception was thrown or not—ideal for releasing locks or closing files.
<?php
declare(strict_types=1);
class InsufficientBalanceException extends RuntimeException {}
function withdraw(float $balance, float $amount): float
{
if ($amount <= 0) {
throw new InvalidArgumentException('Withdrawal amount must be positive.');
}
if ($amount > $balance) {
throw new InsufficientBalanceException('Account balance is too low.');
}
return $balance - $amount;
}
try {
echo "Remaining: $" . withdraw(50.00, 75.00) . PHP_EOL;
} catch (InsufficientBalanceException | InvalidArgumentException $e) {
echo "Transaction declined: " . $e->getMessage() . PHP_EOL;
} finally {
echo "Audit log flushed." . PHP_EOL;
}
PHP 8 lets you catch multiple exception types in one catch block using the pipe | separator, and even omit the variable name (catch (InsufficientBalanceException)) when you do not need $e.
Extend RuntimeException or DomainException to create meaningful application errors that callers can catch selectively. In production, log full details ($e->getMessage(), file, line) to your server log and return only a safe generic message to the user.
catch (Throwable $e) {} blocks: Hiding failures silently makes bugs nearly impossible to diagnose. Always log or rethrow.catch (Throwable $e) before specific catches: PHP matches the first compatible catch block, so a broad Throwable or Exception catch at the top makes later specific catches unreachable.$e->getTraceAsString() to end users: Stack traces reveal file paths and SQL details. Show friendly messages in HTTP responses and log traces privately.Exception and Throwable?Throwable is the top-level interface implemented by both Exception (user/library exceptions) and Error (internal PHP type or parse errors). Catch Throwable in top-level global handlers.
InvalidArgumentException vs RuntimeException?Throw InvalidArgumentException when a caller passes bad input arguments, and RuntimeException when an external operation (network, disk, DB) fails at runtime.
finally blocks run even if try executes a return statement?Yes. PHP executes the finally block right before actually returning control to the caller.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.