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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站