【问题标题】:How to implement exception chaining in PHP如何在 PHP 中实现异常链
【发布时间】:2011-02-06 01:21:44
【问题描述】:

PHP 异常的构造函数有第三个参数,documentation 表示:

$previous: The previous exception used for the exception chaining. 

但我不能让它工作。我的代码如下所示:

try
{
    throw new Exception('Exception 1', 1001);
}
catch (Exception $ex)
{
    throw new Exception('Exception 2', 1002, $ex);
}

我希望抛出异常 2,并且我希望它会附加异常 1。但我得到的只是:

Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in ...

我做错了什么?

【问题讨论】:

    标签: php exception chaining


    【解决方案1】:

    第三个参数需要5.3.0版本。

    【讨论】:

      【解决方案2】:

      在 5.3 之前,您可以创建自己的自定义异常类。也建议这样做,我的意思是如果我 catch (Exception $e) 那么我的代码必须处理所有异常,而不是只处理我想要的异常,代码解释得更好。

      
          class MyException extends Exception
          {
          protected $PreviousException;
      
          public function __construct( $message, $code = null, $previousException = null )
          {
              parent::__construct( $message, $code );
              $this->PreviousException = $previousException;
          }
          }
      
          class IOException extends MyException { }
      
          try
          {
          $fh = @fopen("bash.txt", "w");
          if ( $fh === false)
              throw new IOException('File open failed for file `bash.txt`');
          }
          catch (IOException $e)
          {
          // Only responsible for I/O related errors
          }
      

      【讨论】:

        【解决方案3】:

        我明白了:

        Uncaught exception 'Exception' with message 'Exception 1' ...
        
        Next exception 'Exception' with message 'Exception 2' in ...
        

        你使用 php > 5.3 吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-12
          • 1970-01-01
          • 1970-01-01
          • 2021-05-20
          • 1970-01-01
          • 2011-04-07
          • 2023-03-11
          相关资源
          最近更新 更多