An Exception is an object that describes an error or unexpected behavior in a PHP script. Exceptions are thrown by many PHP functions and classes, and you can even throw your own!
Handling exceptions prevents your script from completely crashing and showing an ugly fatal error to the user.
Exceptions are handled using try...catch blocks.
try: A block of code in which an exception might be generated.throw: If an error is detected inside the try block, the throw keyword triggers an exception object.catch: A block of code that "catches" the exception and decides how to handle it gracefully.
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
// Manually trigger an exception!
throw new Exception("Division by zero is mathematically impossible!");
}
return $dividend / $divisor;
}
try {
// We try to execute code that might fail
echo divide(5, 0);
echo "This line will never execute because an exception was thrown.";
} catch(Exception $e) {
// We catch the error object and print its message
echo "Error Caught: " . $e->getMessage();
}
?>
The try...catch statement can optionally include a finally block.
Code inside the finally block will always execute, regardless of whether an exception was thrown and caught or not. This is perfect for cleaning up resources, like closing a database connection or a file!
try {
// Code that might throw an exception
} catch(Exception $e) {
// Code to handle the exception
} finally {
// Code that ALWAYS runs
}
Which keyword is used to manually generate and send an exception object in PHP?