Error handling is a crucial part of ensuring robustness in PHP development. Using exceptions allows centralized management of error logic, improving code readability and maintainability. Especially within custom functions, throwing and catching exceptions enables the program to gracefully handle various error scenarios.
First, create a custom function and throw an exception where an error might occur. For example, this function performs division and throws an exception if the divisor is zero:
function divide($num1, $num2) {
if ($num2 == 0) {
throw new Exception("Division by zero is undefined.");
}
return $num1 / $num2;
}
Use set_exception_handler() to register a global exception handler that can catch uncaught exceptions and handle them uniformly:
set_exception_handler(function($exception) {
echo "Error: " . $exception->getMessage() . "\n";
});
When calling the custom function, wrap it in a try-catch block to catch exceptions and respond accordingly:
try {
$result = divide(10, 0);
} catch (Exception $e) {
echo "Division by zero error: " . $e->getMessage() . "\n";
}
The example below combines the above steps and demonstrates handling division by zero errors using exception handling:
<?php
function divide($num1, $num2) {
if ($num2 == 0) {
throw new Exception("Division by zero is undefined.");
}
return $num1 / $num2;
}
set_exception_handler(function($exception) {
echo "Error: " . $exception->getMessage() . "\n";
});
try {
$result = divide(10, 0);
} catch (Exception $e) {
echo "Division by zero error: " . $e->getMessage() . "\n";
}
?>
When running the above code, since the divisor is zero, an exception is thrown and caught by the try-catch block, resulting in the following error message:
Division by zero error: Division by zero is undefined.
Using exception handling in custom PHP functions to catch errors centralizes and clarifies error handling, improving code robustness. By properly using throw to raise exceptions, set_exception_handler to register a handler, and try-catch blocks to capture exceptions, you can prevent your program from unexpectedly terminating due to errors and enhance user experience.