搜索
首页后端开发PHP7php5和php7的异常处理机制(thinkphp5 异常处理的分析)

本篇文章主要给大家介绍php5和php7的异常处理机制(thinkphp5 异常处理的分析),希望对需要的朋友有所帮助!

1.php异常和错误

在其他语言中,异常和错误是有区别的,但是PHP,遇见自身错误时,会触发一个错误,而不是跑出异常。并且,php大部分情况,都会触发错误,终止程序执行,在php5中,try catch是没有办法处理错误的。

php7是可以捕获错误的;

1.1 php5 错误异常

// 1.异常处理
try{
  throw new Exception("Error Processing Request", 1);
}catch ( Exception $e){
  echo $e->getCode().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getMessage().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getLine().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getFile().'076402276aae5dbec7f672f8f4e5cc81';
}

返回:

1
Error Processing Request
158
E:\phpwebenv\PHPTutorial\WWW\test\index.php

// 2.结果php错误处理机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
echo 'a4b561c25d9afb9ac8dc4d70affff419 Custom error:0d36329ec37a2cc24d42c7229b69747a'.$error.':'.$errstr.'076402276aae5dbec7f672f8f4e5cc81';
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().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getMessage().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getLine().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getFile().'076402276aae5dbec7f672f8f4e5cc81';
}

结果:
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 '0141e64b460264de306a9735a1994788';
  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().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getMessage().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getLine().'076402276aae5dbec7f672f8f4e5cc81';
  echo $e->getFile().'076402276aae5dbec7f672f8f4e5cc81';
}

结果:

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的异常处理

// 处理致命错误:脚本结束后执行
function shutdown_function(){
    $e = error_get_last();
    echo 'e03b848252eb9375d56be284e690e873';
    var_dump($e);
}
register_shutdown_function('shutdown_function');
// 结果php错误处理机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
    echo 'a4b561c25d9afb9ac8dc4d70affff419 Custom error:0d36329ec37a2cc24d42c7229b69747a'.$error.':'.$errstr.'076402276aae5dbec7f672f8f4e5cc81';
    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().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getMessage().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getLine().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getFile().'076402276aae5dbec7f672f8f4e5cc81';
}
结果:
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 &#39;catch Error:&#39;.$e->getCode().&#39;:&#39;.$e->getMessage().&#39;<br/>&#39;;


}

set_exception_handler(&#39;exception_handler&#39;);

fun();

总结: Throwable 是Error 和 Exception 的基类,在php7中,如果既想捕获异常有需要捕获错误

try{
    fun();
}catch ( Throwable $e){
    echo $e->getCode().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getMessage().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getLine().'076402276aae5dbec7f672f8f4e5cc81';
    echo $e->getFile().'076402276aae5dbec7f672f8f4e5cc81';
}

 3. thinkphp5框架的错误处理:

 在异常错误处理类: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']);
    }
当程序出现错误时,会执行这些异常、错误的函数;

链接数据库后,处理异常的是:

/**
     * 连接数据库方法
     * @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[&#39;params&#39;]) && is_array($config[&#39;params&#39;])) {
                $params = $config[&#39;params&#39;] + $this->params;
            } else {
                $params = $this->params;
            }
            // 记录当前字段属性大小写设置
            $this->attrCase = $params[PDO::ATTR_CASE];

            // 数据返回类型
            if (isset($config[&#39;result_type&#39;])) {
                $this->fetchType = $config[&#39;result_type&#39;];
            }
            try {
                if (empty($config[&#39;dsn&#39;])) {
                    $config[&#39;dsn&#39;] = $this->parseDsn($config);
                }
                if ($config[&#39;debug&#39;]) {
                    $startTime = microtime(true);
                }
                $this->links[$linkNum] = new PDO($config[&#39;dsn&#39;], $config[&#39;username&#39;], $config[&#39;password&#39;], $params);
                if ($config[&#39;debug&#39;]) {
                    // 记录数据库连接信息
                    Log::record(&#39;[ DB ] CONNECT:[ UseTime:&#39; . number_format(microtime(true) - $startTime, 6) . &#39;s ] &#39; . $config[&#39;dsn&#39;], &#39;sql&#39;);
                }
            } catch (\PDOException $e) {
                if ($autoConnection) {
                    Log::record($e->getMessage(), &#39;error&#39;);
                    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. php发生错误时,资源释放

php是解释性脚本,每个php页面都是一个独立的执行程序,不管用什么方式只要执行完了(包括die(),exit(),致命错误终止程序),都会把结果返回给服务器,都会关闭。程序都关闭了,资源当然会被释放;

unset();当多个变量名或者对象名指向一块存储地址时,unset()函数的作用仅仅是销毁变量名和存储地址的指向而已,当仅有一个变量名或者对象名,unset销毁的是指定的存储地址上的内容;

析构方法:当实例化的对象,没有其他变量或对象名指向时,就会执行此方法;或者是在脚本结束后,释放对象资源时,执行此方法;

相关推荐:

PHP7和PHP5在安全上的区别(实例)

PHP7 的抽象语法树(AST)带来的变化

PHP7语言的执行原理(PHP7源码分析)

PHP 7.4预计将在2019年12月发布

以上是php5和php7的异常处理机制(thinkphp5 异常处理的分析)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:cnblogs。如有侵权,请联系admin@php.cn删除

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),