PHP failed to capture parse error?
漂亮男人
漂亮男人 2017-05-16 13:00:20
0
3
427

The code is as follows. The registered error handling function register_shutdown_function is not executed, which is very strange


    error_reporting(-1);
    ini_set('display_errors', 1);

    set_error_handler(function(){
        echo "error handler execute";
    }, E_ALL);

    set_exception_handler(function(){
        echo "exception handler execute";
    });

    register_shutdown_function(function(){
        echo "shutdown function execute";
    });

    try{
        0$a;
    }catch(exception $e){
        echo "catch exception";
    }finally{
        echo "finally ";
    }

Execution results:


Parse error: syntax error, unexpected '$a' (T_VARIABLE) in C:\Users\mao\Documents\php\index.php on line 18

PHP Parse error: syntax error, unexpected '$a' (T_VARIABLE) in C:\Users\mao\Documents\php\index.php on line 18
[Finished in 0.1s]

0$a was written intentionally, why were the exceptions not handled?

漂亮男人
漂亮男人

reply all(3)
洪涛

You can try PHP7’s try{}catch(Error){}

http://php.net/manual/en/clas...

ParseError extends Error 
PHPzhong

Syntax errors are the first to be warned by the system and are system-level exceptions. As soon as the system warns, the entire program has never been run.

迷茫

First of all, you must understand that exceptions and errors are different. Exceptions are situations outside of normal logic, while errors refer to errors during runtime! Once an error occurs, the entire code will no longer be executed and your program will hang. If an exception occurs, you can use try catch to catch it, and the program can continue to run!

Obviously, your code has a syntax error, so this program cannot be executed at all, which means that you triggered an error instead of an exception. So how to achieve the effect you want? First we need to solve the syntax problem, look at the code below

    error_reporting(-1);
    ini_set('display_errors', 1);

    set_error_handler(function(){
        echo "error handler execute";
    }, E_ALL);

    set_exception_handler(function(){
        echo "exception handler execute";
    });

    register_shutdown_function(function(){
        echo "shutdown function execute";
    });

    try{
        echo $a;
    }catch(exception $e){
        echo "catch exception";
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template