15

PHP 异常的构造函数有第三个参数,文档说:

$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 ...

我究竟做错了什么?

4

3 回答 3

23

第三个参数需要 5.3.0 版本。

于 2010-04-09T08:50:17.867 回答
3

在 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
    }
于 2013-05-12T22:32:10.927 回答
1

我得到:

Uncaught exception 'Exception' with message 'Exception 1' ...

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

您使用 php > 5.3 吗?

于 2010-04-09T08:52:23.790 回答