Do not throw exception in exception_handler function and __destruct without try-catch

Do NOT throw exception in exception_handler function, if you do it like below, 
the error “Fatal error: Exception thrown without a stack frame in Unknown on line 
0” will occur
set_exception_handler('handle_exception');
function handle_exception($e)
{
    throw new Exception('throwed in handle_exception');
}
throw new Exception('error occur');

if you try-catch the Exception in exception_handler function, it will be ok, the below code will work well

set_exception_handler('handle_exception');
function handle_exception($e)
{
    try {
        throw new Exception('throwed in handle_exception');
    }
    catch (Exception $e) {
        die('catch exception in handle_exception function');
    }
}
throw new Exception('error occur');
Do NOT throw Exception in __destruct like below, or “Fatal error: Exception thrown
without a stack frame in Unknown on line 0” will occur.
class Test {
    function __construct () {}
    function __destruct() {
        throw new Exception('throwed in __destruct');
    }
}
$test = new Test();

but it will work well when try-catch it like below

class Test {
    function __construct () {}
    function __destruct() {
        try {
            throw new Exception('throwed in __destruct');
        }
        catch (Exception $e) {
            die('catch exception in __destruct');
        }
        
    }
}
$test = new Test();

1 thought on “Do not throw exception in exception_handler function and __destruct without try-catch”

Comments are closed.