Error and Exception Handling
PHP exceptions let a script signal and gracefully respond to runtime problems, rather than crashing with an unhandled fatal error.
try, catch, throw
Code that might fail goes inside a try block. throw raises an exception object, which a matching catch block can handle without halting the rest of the script.
function divide(float $a, float $b): float {
if ($b === 0.0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nCalculation attempted.";
}
Common Mistakes
- Catching Exception too broadly, hiding the specific type of error that actually occurred.
- Forgetting that finally always runs, whether or not an exception was thrown or caught.
- Throwing plain strings instead of proper Exception objects, which PHP does not support directly.
- Not creating custom exception classes for domain-specific errors, making error handling less precise across a larger application.
Professional Tip
Create custom exception classes (extending PHP's built-in Exception) for meaningful application errors, like class InsufficientFundsException extends Exception {}. This lets calling code catch specific problems distinctly rather than treating every failure identically.
Your Turn
Create a custom exception class called InsufficientFundsException, and use it inside a withdraw() function that throws it when a withdrawal amount exceeds the available balance.
Mini Quiz
In a try/catch/finally block, when does the finally block execute?
finally block runs regardless of what happened in try or catch, making it the right place for cleanup code that must always execute.