Object-Oriented PHP · 8 min read · Beginner
Exceptions & Resilient Error Handling
Catch specific exception types with try/catch/finally, throw descriptive InvalidArgumentException errors, and keep apps crash-proof.
What you'll learn
- Throw descriptive built-in or custom Exception classes
- Handle failures cleanly with try / catch / finally
Throwing typed exceptions (InvalidArgumentException, RuntimeException) lets callers catch and handle specific failures cleanly while finally guarantees cleanup always runs.
Fill-in-the-Blank Exercise
Throw & Catch a PHP Exception
Throw an InvalidArgumentException and catch it.
if ($score < 0) {
new InvalidArgumentException('Score cannot be negative');
}
try {
validate(-5);
} (InvalidArgumentException $e) {
echo $e->getMessage();
}Try It Yourself
PHPTyped Exception Handling in PHP 8
PHP 8 Output (WebAssembly)
Click Run PHP to execute real PHP 8 right in your browser.
Check Your Understanding
Score: 0 / 1
1. Which method on a PHP Exception returns the human-readable error string?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.