PHP Exceptions
Exceptions provide a structured way to handle errors that occur during script execution, letting you separate error-handling code from normal logic. When something goes wrong, you can throw an exception, which can then be caught and handled gracefully.
PHP uses try, catch, and optionally finally blocks to manage exceptions. Code that might fail is placed in try, error-handling code goes in catch, and finally runs regardless of whether an exception occurred.
try {
// risky code
} catch (Exception $e) {
// handle error
} finally {
// always runs
}Throwing and catching exceptions
throw new Exception("message") raises an exception. A matching catch (Exception $e) block catches it and can access the error message with $e->getMessage().
The finally block
Code inside finally always runs, whether or not an exception was thrown, making it useful for cleanup tasks like closing a file or database connection.
<?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();
}
?>Error: Cannot divide by zeroThe exception thrown inside divide() is caught, and its message is displayed instead of crashing the script.
<?php
try {
echo "Trying...";
throw new Exception("Oops");
} catch (Exception $e) {
echo " Caught: " . $e->getMessage();
} finally {
echo " Done.";
}
?>Trying... Caught: Oops Done.The finally block runs after the catch block regardless of the outcome.
Key points
- throw raises an exception when something goes wrong.
- try/catch lets you handle errors without crashing the script.
- getMessage() retrieves the error message from a caught exception.
- finally always runs, whether or not an exception occurred.
