程式碼如下,已經(jīng)註冊了錯誤處理函數(shù)register_shutdown_function都沒有執(zhí)行,很奇怪
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 ";
}
執(zhí)行結(jié)果:
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是故意寫的,為什麼異常都沒有被處理呢?
可以試試PHP7的try{}catch(Error){}
http://php.net/manual/en/clas...
ParseError extends Error
語法錯誤是最先被系統(tǒng)做出警告,屬於系統(tǒng)層級的異常,系統(tǒng)一警告,整個程式根本就都沒運作過。
首先要明白異常跟錯誤是不一樣的,異常是出現(xiàn)正常邏輯之外的情況,而錯誤是指運行時出錯了!一旦出現(xiàn)錯誤,整個程式碼就不會再執(zhí)行,你的程式也就掛了。而出現(xiàn)異常你可以使用try catch捕捉到,而且程式還可以繼續(xù)運作!
很明顯,你的程式碼有語法錯誤,那麼這段程式根本執(zhí)行不了,也就是說你這裡是觸發(fā)了一個錯誤而不是異常。那麼要如何達到你想要的效果呢?首先就要解決文法問題,看下面程式碼
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";
}