douhui8025 2011-10-21 23:01
浏览 72
已采纳

在异常处理程序中抛出异常

I have a script with an exception handler. This exception handler cleans up a couple connections, prior to the script exiting after an exception.

I would like to re-throw the exception from this exception handler so that it is handled by PHP's own last-resort exception handler, where the error is written to PHP's error log, or whatever the default is, as configured in PHP.ini.

Unfortunately, this doesn't seem like a possibility, as outlined here:

http://www.php.net/manual/en/function.set-exception-handler.php#68712

Will cause a Fatal error: Exception thrown without a stack frame

Is there another way to bubble the error up the stack so that PHP handles it after my exception handler is done cleaning up?

  • 写回答

5条回答

  • donglu1913 2011-10-29 14:29
    关注

    You can not re-throw from the exception handler, however, there are other places you can. For example you can de-couple the re-throw from the handler by encapsulating things into a class of it's own and then use the __destruct() function (PHP 5.3, Demo):

    <?php
    
    class ExceptionHandler
    {
        private $rethrow;
        public function __construct()
        {
            set_exception_handler(array($this, 'handler'));
        }
        public function handler($exception)
        {
            echo  "cleaning up.
    ";
            $this->rethrow = $exception;
        }
        public function __destruct()
        {
            if ($this->rethrow) throw $this->rethrow;
        }
    }
    
    $handler = new ExceptionHandler;
    
    throw new Exception();
    

    Put this into my error log:

    [29-Oct-2011 xx:32:25] PHP Fatal error: Uncaught exception 'Exception' in /.../test-exception.php:23
    Stack trace:
    #0 {main}
    thrown in /.../test-exception.php on line 23
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿