This article mainly introduces the exception handling mechanism of php5 and php7 (analysis of thinkphp5 exception handling). I hope it will be helpful to friends in need!
1.php exceptions and errors
In other languages, exceptions and errors are different, but PHP will trigger an error when it encounters its own error. Instead of throwing an exception. Moreover, in most cases, PHP will trigger an error and terminate the program execution. In PHP5, try catch has no way to handle errors.
php7 can capture errors;
1.1 php5 error exception
// 1.异常处理 try{ throw new Exception("Error Processing Request", 1); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 返回: 1 Error Processing Request 158 E:\phpwebenv\PHPTutorial\WWW\test\index.php // 2.结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); trigger_error('error_msg'); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Custom error:1024:error_msg Error on line 164 in E:\phpwebenv\PHPTutorial\WWW\test\index.php //3. 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre/>'; var_dump($e); } register_shutdown_function('shutdown_function'); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Fatal error: Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\ test\index.php:172 Stack trace: #0 {main} thrown in E:\phpwebenv\PHPTutorial\WWW\test\index.php on line 172 array(4) { ["type"]=> int(1) ["message"]=> string(131) "Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\test\index.php:172 Stack trace: #0 {main} thrown" ["file"]=> string(43) "E:\phpwebenv\PHPTutorial\WWW\test\index.php" ["line"]=> int(172) } 以上方法可以看出,php没有捕获到异常,只能依赖set_error_handler()和register_shutdown_function();来处理,set_error_handler只能接受 异常和非致命的错误。register_shutdown_function():主要针对die()或致命错误,即程序终结后执行;所以php5没有很好的异常处理机制。
1.2 php7 exception handling
// 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre class="brush:php;toolbar:false">'; var_dump($e); } register_shutdown_function('shutdown_function'); // 结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Error $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: 0 Call to undefined function fun() 172 E:\phpwebenv\PHPTutorial\WWW\test\index.php NULL register_shutdown_function();没有捕获到异常
// 2. 如果不用try catch 捕获 function exception_handler( Throwable $e){ echo 'catch Error:'.$e->getCode().':'.$e->getMessage().'<br/>'; } set_exception_handler('exception_handler'); fun();
Summary: Throwable is the base class of Error and Exception. In php7, if you want to catch exceptions, you need to catch errors
try{ fun(); }catch ( Throwable $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; }
3. Error handling of thinkphp5 framework:
在异常错误处理类:Error有这个处理 // 注册错误和异常处理机制 \think\Error::register(); /** * 注册异常处理 * @return void */ public static function register() { error_reporting(E_ALL); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); } 当程序出现错误时,会执行这些异常、错误的函数;
After connecting to the database, the exception is handled as follows:
/** * 连接数据库方法 * @access public * @param array $config 连接参数 * @param integer $linkNum 连接序号 * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) * @return PDO * @throws Exception */ public function connect(array $config = [], $linkNum = 0, $autoConnection = false) { if (!isset($this->links[$linkNum])) { if (!$config) { $config = $this->config; } else { $config = array_merge($this->config, $config); } // 连接参数 if (isset($config['params']) && is_array($config['params'])) { $params = $config['params'] + $this->params; } else { $params = $this->params; } // 记录当前字段属性大小写设置 $this->attrCase = $params[PDO::ATTR_CASE]; // 数据返回类型 if (isset($config['result_type'])) { $this->fetchType = $config['result_type']; } try { if (empty($config['dsn'])) { $config['dsn'] = $this->parseDsn($config); } if ($config['debug']) { $startTime = microtime(true); } $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); if ($config['debug']) { // 记录数据库连接信息 Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql'); } } catch (\PDOException $e) { if ($autoConnection) { Log::record($e->getMessage(), 'error'); return $this->connect($autoConnection, $linkNum); } else { throw $e; } } } return $this->links[$linkNum]; } 当数据库链接失败后,可以重新链接或者直接抛出异常; /** * 析构方法 * @access public */ public function __destruct() { // 释放查询 if ($this->PDOStatement) { $this->free(); } // 关闭连接 $this->close(); } 当执行sql失败后,调用析构方法,关闭数据库链接;
4. When an error occurs in php, the resource is released
php is an explanatory script. Each PHP page is an independent execution program. No matter what method is used, as long as it is executed (including die(), exit(), fatal error termination program), the result will be returned to the server and it will be closed. When the program is closed, the resources will of course be released;
unset(); When multiple variable names or object names point to a storage address, the function of the unset() function is only to destroy the pointers of the variable names and storage addresses. That’s it, when there is only one variable name or object name, unset destroys the content at the specified storage address;
Destruction method: When the instantiated object has no other variables or object names pointing to it, it This method will be executed; or this method will be executed when the object resources are released after the script ends;
Related recommendations:
《The difference in security between PHP7 and PHP5 (example) )》
《Changes brought about by PHP7’s Abstract Syntax Tree (AST)》
《The execution principle of PHP7 language (PHP7 source code analysis )》
《PHP 7.4 is expected to be released in December 2019》
The above is the detailed content of Exception handling mechanism of php5 and php7 (analysis of thinkphp5 exception handling). For more information, please follow other related articles on the PHP Chinese website!