Python Exceptions, Throwables & Custom Error Fences
Modern PHP handles errors and exceptions through the unified Throwable interface. Learn try...catch...finally blocks, throwing custom Exception classes, catching multiple exception types, and global error handling.
"An exception is like an emergency stop cord on a train. When an impossible condition occurs (out of funds, database down), the conductor pulls the cord (throw), and the emergency response team (catch) safely evacuates passengers without a derailment."
Deep Dive: How It Works
The Throwable Hierarchy: Both Exception and Error (e.g. TypeError, ParseError) implement the Throwable interface.
Try-Catch-Finally: try runs code; catch intercepts matching exception types; finally executes cleanup unconditionally.
Custom Exceptions: Create domain exceptions by extending Exception (e.g. class PaymentFailedException extends Exception {}).
Exception Chaining: throw new ServiceException("Lookup failed", 0, $previousException) preserves root cause.
Syntax Blueprint
<?php
try {
throw new InvalidArgumentException("Port must be positive");
} catch (InvalidArgumentException $e) {
echo "Handled: " . $e->getMessage();
} finally {
// Guaranteed cleanup
}Wrap risky code in try blocks, handle specific exceptions in catch, and release resources in finally.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using empty catch (Exception $e) {} blocks that silently swallow errors.Why it happens: Hides critical system failures and makes debugging impossible.
How to fix: Always log exceptions (error_log) or rethrow them if unrecoverable.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Throw and Catch Division by Zero Exception
Write a function safeDivide(float $a, float $b): float.
If $b == 0.0, throw new InvalidArgumentException("Division by zero").
Return $a / $b.
Wrap a call to safeDivide(10, 0) in a try-catch block and print "Error: " followed by the exception message.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.