php 处理错误和异常技巧
作者:互联网
set_time_limit(0); ini_set('memory_limit','1024M'); function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); function customError($errno, $errstr) { throw new Exception($errstr); } set_error_handler("customError", E_ALL); try{ //throw new Exception('Uncaught Exception'); trigger_error("Cannot divide by zero", E_USER_ERROR); }catch(Exception $e){ throw new Exception($e->getMessage()); } echo '111'; exit;
上面把产生错误(包含警告)时,抛出异常,就把错误处理交给自定义的异常处理方法处理了
try{ ... }catch(Exception $e){ ... } try段里如果抛出异常,有catch,则对应catch处理;无catch,则set_exception_handler自定义异常处理,如无自定义异常处理,则选择php语言本身的异常处理方式。try段里如果产生错误,有set_error_handler自定义处理处理,则选择定义处理处理,如无,则选择php语言本身的错误处理方式。很明显上面代码set_error_handler自定义处理是抛出异常,等同于最终统一了错误和异常处理方式都是交给set_exception_handler自定义的异常处理。
上面代码可以不用显示catch语句,效果等同。
set_time_limit(0); ini_set('memory_limit','1024M'); function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); function customError($errno, $errstr) { throw new Exception($errstr); } set_error_handler("customError", E_ALL); try{ //throw new Exception('Uncaught Exception'); trigger_error("Cannot divide by zero", E_USER_ERROR); }
echo '111'; exit;
标签:exception,set,技巧,自定义,Exception,handler,error,php,处理错误 来源: https://www.cnblogs.com/hnhycnlc888/p/10964579.html