PHP - 是否可以在 __destruct() 方法中使用自定义异常处理程序

有没有办法在类的方法中使用自定义异常处理程序,而不是默认异常处理程序__destruct?


例如:


function myExceptionHandler($e)

{

    echo "custom exception handler";

    if(is_object($e) && method_exists($e,'getMessage'))

        echo $e->getMessage();

}

set_exception_handler('myExceptionHandler');

class MyClass {

    public function __construct()

    {

        // myExceptionHandler handles this exception

        //throw new Exception("Exception from " . __METHOD__);

    }


    public function doStuff()

    {

        // myExceptionHandler handles this exception

        //throw new Exception("Exception from " . __METHOD__);

    }


    public function __destruct()

    {

        // default exception handler 

        throw new Exception("Exception from " . __METHOD__);

    }


}


$myclass = new MyClass();

$myclass->doStuff();

即使在方法set_exception_handler内调用__destruct,仍使用默认处理程序:


    public function __destruct()

    {

        $callable = function($e)

        {

            echo "custom exception handler".PHP_EOL;

            if(is_object($e) && method_exists($e,'getMessage'))

                echo $e->getMessage();

        };

        set_exception_handler($callable);

        throw new Exception("Exception from " . __METHOD__); // default exception handler

    }


慕村9548890
浏览 188回答 2
2回答

胡说叔叔

从手册页笔记:尝试从析构函数(在脚本终止时调用)抛出异常会导致致命错误。因此,首先在析构函数中使用异常可能是个坏主意。当脚本完成处理抛出的异常时,可能没有任何代码。也许这段代码最好放在close()类的方法中。

慕莱坞森

也许是这样的?<?phpclass MyException extends Exception {&nbsp; &nbsp; public function __construct() {&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct('my exception');&nbsp; &nbsp; }}class MyClass {&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // myExceptionHandler handles this exception&nbsp; &nbsp; &nbsp; &nbsp; //throw new Exception("Exception from " . __METHOD__);&nbsp; &nbsp; }&nbsp; &nbsp; public function doStuff()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // myExceptionHandler handles this exception&nbsp; &nbsp; &nbsp; &nbsp; //throw new Exception("Exception from " . __METHOD__);&nbsp; &nbsp; }&nbsp; &nbsp; public function __destruct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // default exception handler&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; throw new MyException();&nbsp; &nbsp; }}$myclass = new MyClass();$myclass->doStuff();
打开App,查看更多内容
随时随地看视频慕课网APP