Things go wrong at runtime — a file might not exist, a value from a form might not be what was expected. PHP's try/catch lets a script handle that gracefully instead of crashing outright.
<?php
function divide($a, $b) {
if ($b === 0) {
throw new Exception("Cannot divide by zero.");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>throw raises an exception; the nearest surrounding catch block that matches its type intercepts it, and the script keeps running from there instead of stopping.
Code inside finally always runs, whether an exception was thrown or not — useful for cleanup that must happen either way, like closing a file:
<?php
try {
echo divide(10, 2);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nDone.";
}
?>PHP has several built-in exception types, and you can catch a more specific one before a general Exception:
<?php
try {
$result = 10 / 0; // DivisionByZeroError, not a regular Exception
} catch (DivisionByZeroError $e) {
echo "Specifically caught: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
}
?>Specific catch blocks go first
Order matters when catching multiple types — PHP checks catch blocks top to bottom and uses the first one that matches, so a specific type should always come before a more general one that would otherwise catch it first.
An uncaught error on a live PHP site can expose a raw error message — sometimes including file paths or database details — directly to a visitor. Wrapping risky operations (file access, database queries, anything talking to something outside your own script) in try/catch is what turns that into a clean, controlled message instead.