Exceptions & Error Handling
Prerequisites: Enums
try/catch/finally handle recoverable failures — thrown as
objects, exactly like Java and C#.
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 "Done";
}
A custom exception extends Exception (or a more specific
built-in subclass) for domain-specific errors:
class InsufficientFundsException extends RuntimeException {}
throw new InsufficientFundsException("Balance too low");
Common mistakes
- Catching the generic
Exception(orThrowable) everywhere "to be safe" — catch the specific type you actually expect and know how to handle.