PHP Exceptions
PHP Exceptions: Structured Error Handling with try, catch, and finally
A 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.
Using try, catch, and finally
Wrap 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.
Custom Exceptions and Logging
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.
Common Mistakes to Avoid
- Swallowing exceptions with empty
catch (Throwable $e) {}blocks: Hiding failures silently makes bugs nearly impossible to diagnose. Always log or rethrow. - Putting
catch (Throwable $e)before specific catches: PHP matches the first compatiblecatchblock, so a broadThrowableorExceptioncatch at the top makes later specific catches unreachable. - Exposing
$e->getTraceAsString()to end users: Stack traces reveal file paths and SQL details. Show friendly messages in HTTP responses and log traces privately.
Frequently Asked Questions
What is the difference between 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.
When should I throw InvalidArgumentException vs RuntimeException?
Throw InvalidArgumentException when a caller passes bad input arguments, and RuntimeException when an external operation (network, disk, DB) fails at runtime.
Do finally blocks run even if try executes a return statement?
Yes. PHP executes the finally block right before actually returning control to the caller.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.