Error
Errors are inevitable in writing programs. How to find, locate and correct errors is a science. Today I will talk to you about the errors and exceptions after php7.
Classification of errors
General errors are divided into syntax errors, runtime errors, and logic errors. Syntax and runtime errors are easy to troubleshoot, but logic errors are not so simple. I have written the comparison operation == as the assignment operation = many times when making judgments. It is difficult for people like me to find it. Generally, as you gain more experience (you step on more pitfalls), it will become easier to find logical errors.
Control error output
It is generally recommended to turn on error output during the development stage to facilitate timely detection of errors. It is recommended to turn off errors during the online stage for the sake of safety and beauty. output.
php provides a parameter display_errors to control the output of errors to the browser and cli. There are two ways to modify it, by modifying the php.ini file or using the ini_set function. The following shows the code that uses ini_set to set up masking error output.
<?php ini_set('display_errors', 0); echo $a; echo 0; date(); echo 1;
The program will output 01 normally, but will not output error information.
Error reporting level
Generally divided into 4 categories
parse syntax error
errorfatal error
warning warning level error
notice attention level error
In the php.ini configuration file, there is the option error_reporting, which is used to control what level of errors are output. Common ones include E_ALL, E_WARNING, and E_NOTICE.
You can dynamically control the error level output through the function error_reporting().
# 输出所有级别错误 error_reporting(E_ALL); # 输出所有级别除了E_NOTICE error_reporting(E_ALL & ~E_NOTICE); # 输出所有级别除了E_NOTICE和E_WARNING error_reporting(E_ALL & ~(E_NOTICE | E_WARNING));
The difference between display_errors and error_reporting
display_errors is used to control whether errors are output, while error_reporting is used to control the level of output mistake. Usually they will use
ini_set('display_errors', 0); // 关闭错误输出 error_reporting(E_ALL); // 输出所有级别的错误信息
The above configuration is usually in the online stage, which blocks all error output, but records errors in the PHP error log. The path to the error log is determined by the option error_log.
If error_reporting is set to 0, no errors will be output or error logs will be recorded.
The impact of errors on the program
When the program has syntax errors, the program will not be executed. When there is an error level error, the program will stop executing downward. Notice, and warning level errors will not affect the downward execution of the program.
error_reporting(E_ALL); // 输出所有级别的错误信息 echo $a; echo 0; date(); echo 1; new a; echo 2;
This program will output 0 and 1, but not 2.
User-defined error
The trigger_error() function can generate a user-level error. Error levels include E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, etc.
<?php trigger_error('这是notice级别错误', E_USER_NOTICE); trigger_error('warning错误', E_USER_WARNING); trigger_error('deprecated', E_USER_DEPRECATED); trigger_error('error错误', E_USER_ERROR);
Customized error handling
set_error_handler - Set a user-defined error handling function. The function prototype is as follows:
set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] ) : mixed
The The first parameter of the function is a callback function, the prototype is as follows:
handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] ) : bool
error Error level
errstr Error message
errfile Send the wrong file
errline The line number where the error occurred
The following level errors cannot be defined by user-defined functions To handle: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most E_STRICTs generated in the file where the set_error_handler() function is called.
<?php define('DEBUG', false); set_error_handler('error_handler'); if (DEBUG) { ini_set('display_errors', 'On'); } else { ini_set('display_errors', 'Off'); } function error_handler($errLevel, $errInfo, $errFile, $errLine) { echo "ErrorLevel:$errLevel: $errInfo In $errFile ON $errLine" . PHP_EOL; } echo $a;
Exception
异常和错误时有区别的,错误一般是指我们能控制的问题,比如变量名写错了,或者判断条件写的不错,导致死循环。而异常通常指那些难以控制的、意料外的错误,比如mysql连接不上,文件句柄打开失败等情况。
php的异常也是经典的try catch finally,但和一般的异常处理不一样的是,绝大部分的异常需要自行抛出。抛出异常使用throw关键字完成。php也支持捕获多个异常。
<?php class MyError extends Exception { public function printErr () { echo '出错啦'.PHP_EOL; } } class YourError extends Exception { public function printErr () { echo 'errors'.PHP_EOL; } } try { if (mt_rand(0,1)) { throw new MyError('错误'); } else { throw new YourError('错误'); } } catch (MyError $e) { $e->printErr(); } catch (YourError $e) { $e->printErr(); } finally { echo '不管有没有异常,我都会被执行'.PHP_EOL; }
php的异常如果没有捕获,则会报Fatal Error错误,程序不会继续向下执行。
PHP 7 错误处理
PHP 7 改变了大多数错误的报告方式。不同于传统(PHP 5)的错误报告机制,现在大多数错误被作为 Error 异常抛出。 Error 和 Exception 都实现了 Throwable 接口
异常处理
设置默认的异常处理程序,有try/catch捕获的话这个异常函数就不会执行,反之就会执行异常处理函数,而且执行的话,脚本将不会继续执行。
php使用set_exception_handler来设置用户自定义的异常处理函数 ,函数原型如下:
set_exception_handler ( callable $exception_handler ) : callable
回调函数的原型如下:
handler ( Throwable $ex ) : void
下面,我们来写一个异常处理函数
<?php class MyError extends Exception { public function printErr () { echo '出错啦'.PHP_EOL; } } class YourError extends Exception { public function printErr () { echo 'errors'.PHP_EOL; } } try { if (mt_rand(0,1)) { throw new MyError('错误'); } else { throw new YourError('错误'); } } catch (MyError $e) { $e->printErr(); } catch (YourError $e) { $e->printErr(); } finally { echo '不管有没有异常,我都会被执行'.PHP_EOL; }
统一处理错误与异常
学完了错误与异常,知道如何去使用自定义错误处理和异常处理,现在我们就可以统一处理错误与异常了。
<?php class Errors { // 处理非致命错误 static function errorHandle($errLevel, $errInfo, $errFile, $errLine) { echo '错误:'.PHP_EOL; print_r(['file' => $errFile, 'level' => $errLevel, 'line' => $errLine, 'info' => $errInfo]); } // 处理致命错误及异常 static function exceptionHandle(Throwable $ex) { echo '异常:'.PHP_EOL; print_r(['file' => $ex->getFile(), 'level' => $ex->getCode(), 'line' => $ex->getLine(), 'info' => $ex->getMessage()]); } } set_error_handler(['Errors', 'errorHandle']); set_exception_handler(['Errors', 'exceptionHandle']);
The above is the detailed content of Error and exception handling in php7. For more information, please follow other related articles on the PHP Chinese website!