开发者

How to implement exception chaining in PHP

Constructor for PHP's exception has third parameter, documentation says:

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

But I can't make it work. My code looks like this:

try
{
    throw new Exception('Exception 1', 1001);
}
catch (Exception $ex)
{
 开发者_运维问答   throw new Exception('Exception 2', 1002, $ex);
}

I expect Exception 2 to be thrown and I expect that it will have Exception 1 attached. But all I get is:

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

What am I doing wrong?


The third parameter requires version 5.3.0.


Before 5.3 you can just create your own custom exception class. It is also recommended to do this, I mean if I catch (Exception $e) then my code must handle all exceptions rather then just the one I'm wanting, code explains it better.


    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
    }


I get:

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

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

You using php > 5.3 ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜