Try, Catch, and Finally
Handle runtime exceptions gracefully with try/catch/finally blocks.
Exceptions vs Errors
PHP has two ways to signal problems:
- Errors — traditional PHP notices/warnings/fatals (discussed previous lesson)
- Exceptions — objects thrown when something exceptional happens; caught with try/catch
Exceptions are the modern, preferred approach for handling recoverable errors.
Throwing an Exception
Use throw to signal that something went wrong:
<?php
function divide(float $a, float $b): float {
if ($b == 0) {
throw new InvalidArgumentException('Cannot divide by zero');
}
return $a / $b;
}
echo divide(10, 2); // 5
// divide(10, 0); // throws exceptionAll lessons in this course
- PHP Error Types and Reporting
- Try, Catch, and Finally
- Creating Custom Exceptions
- Logging Errors and Best Practices