PHP Exceptions
Exceptions let a PHP program signal that something went wrong and hand control to code that knows how to recover, keeping error handling separate from normal logic.
What an exception is
An exception is an object that represents an error or an unexpected situation. Instead of returning a special value that the caller might ignore, a function can throw an exception. This interrupts normal execution and jumps to a matching handler, so a problem cannot silently slip past. This approach keeps the main flow of a function readable while still dealing with failure cases properly.
PHP uses four keywords for this: try marks a block of code to watch, throw raises an exception, catch handles one that was thrown, and finally runs cleanup code whether or not an error happened.
A basic try and catch
<?php
function divide($a, $b) {
if ($b === 0) {
throw new Exception("Cannot divide by zero.");
}
return $a / $b;
}
try {
echo divide(10, 2); // 5
echo divide(10, 0); // throws
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>The finally block
Code inside a finally block always runs after the try and catch, even if an exception was thrown or the function returned early. It is the natural place to release resources such as closing a file or a database connection, so that cleanup is guaranteed.
Using finally for cleanup
<?php
try {
echo "Opening resource...\n";
throw new Exception("Something failed.");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage() . "\n";
} finally {
echo "Closing resource (always runs).\n";
}
?>Custom exceptions and multiple catch blocks
You can define your own exception classes by extending the built-in Exception class. This lets you catch specific kinds of errors separately and react differently to each one. PHP evaluates catch blocks in order, so list the most specific type first and a more general type last.
A custom exception type
<?php
class NotFoundException extends Exception {}
function findUser($id) {
$users = [1 => "Ada", 2 => "Grace"];
if (!isset($users[$id])) {
throw new NotFoundException("User $id does not exist.");
}
return $users[$id];
}
try {
echo findUser(5);
} catch (NotFoundException $e) {
echo "Not found: " . $e->getMessage();
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage();
}
?>- Throw an exception when a function cannot complete its job as expected.
- Catch only the exceptions you can actually handle; let others propagate upward.
- Use finally for cleanup that must run no matter what.
- Create custom exception classes to distinguish different failure types.
- An uncaught exception stops the script and produces a fatal error.
Exercise: PHP Exceptions
When does code inside a finally block execute?