PHP set_exception_handler() Function
PHP Runtime Error Handling
Definition and Usage
The set_exception_handler() function sets a user-defined exception handler function.
This function returns the name of the previously defined exception handler, or NULL on error. If the function requires parameters, the name should be passed as a string, otherwise the function name can be passed directly as a string or as an array (see the examples below).
Syntax
set_exception_handler(callback $exception_handler): mixed
Parameters
| Parameter | Description |
|---|---|
| exception_handler | Required. The name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). The handler function must accept one parameter, which will be the exception object thrown. |
Technical Details
| Return Value: | Returns the name of the previously defined exception handler, or NULL on error. |
|---|---|
| PHP Version: | PHP 5+ |
| Changelog: | PHP 7: The return type was changed to ?string. Previously returned string or NULL (depending on whether a previous handler was set). |
More Examples
Example 1
How to use set_exception_handler():
<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}
set_exception_handler("myException");
throw new Exception("Uncaught Exception!");
?>
Output of the above code:
Exception: Uncaught Exception!
Example 2
Using set_exception_handler() with a class:
<?php
class MyExceptionHandler {
public function handle($exception) {
echo "Exception: " . $exception->getMessage();
}
}
set_exception_handler(array("MyExceptionHandler", "handle"));
throw new Exception("This exception will be caught by the class handler!");
?>
Related Functions
- restore_exception_handler() - Restores the previously defined exception handler
- set_error_handler() - Sets a user-defined error handler function
- restore_error_handler() - Restores the previously defined error handler
- trigger_error() - Generates a user-level error message
YouTip