PHP Error Handling
Error handling is the process of catching errors raised by your program and then taking appropriate action.
1. Try...Catch
The try...catch statement allows you to define a block of code to be tested for errors while it is being executed.
try {
// Code that may throw an exception
$x = 10 / 0;
} catch (Exception $e) {
// Code that runs if an exception is caught
echo "Unable to divide.";
}
2. The Exception Object
The Exception object contains information about the error or unexpected behavior.
try {
throw new Exception("Something went wrong");
} catch(Exception $e) {
echo "Message: " . $e->getMessage();
}
3. Finally
The finally block will always be executed after the try and catch blocks, regardless of whether an exception was thrown or not.
try {
echo "Process started.<br>";
throw new Exception("Error!");
} catch(Exception $e) {
echo "Error caught.<br>";
} finally {
echo "Process finished.";
}
4. Throwing Exceptions
The throw statement allows you to create a custom error.
function checkNum($number) {
if($number > 1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
} catch(Exception $e) {
echo "Message: " . $e->getMessage();
}