'set_exception_handler' function is used to catch any uncaught exceptions. Since the exception handler set by the method 'set_exception_handler' is called outside of the context where the actual error occurred, it is not possible to recover from the exception. It is mainly used to log the exception messages.
Step 1: Define a function that takes an exception as argument.
function my_exception_handler($e){
    echo "------------------------\n";
    echo "Uncaught exception handler\n";
    echo $e->getMessage();
    echo "\n------------------------\n";
}
Step 2: Set the function ‘my_exception_handler’ as uncaught exception handler.
set_exception_handler('my_exception_handler');
Find the below working application.
uncaught_exception_demo.php
#!/usr/bin/php
<?php 
function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}
function my_exception_handler($e){
    echo "------------------------\n";
    echo "Uncaught exception handler\n";
    echo $e->getMessage();
    echo "\n------------------------\n";
}
set_exception_handler('my_exception_handler');
div(10, 0);
?>
Output
$./uncaught_exception_demo.php 
------------------------
Uncaught exception handler
Division by zero
------------------------
No comments:
Post a Comment