Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
Josef Sábl Avatar asked Apr 09 '10 08:04

Josef Sábl


People also ask

How can I create exception in PHP?

Throwing Exceptions in PHP Throwing a generic exception is almost as simple as it sounds. All it takes is to instantiate an exception object—with the first parameter of the Exception constructor being the error message—and then, "throw" it. The most important thing to take note of is the message.

Can we use try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Can we use try without catch in PHP?

You must use catch with try . Please look php.net manual. PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP.


1 Answers

The third parameter requires version 5.3.0.

like image 71
Matthew Avatar answered Sep 20 '22 17:09

Matthew