I have following piece of code:
function doSomething()
{
try {
doSomeNastyStuff() // throws Exception
} catch(\Exception $e) {
if ($this->errorHandler) {
call_user_func($e);
} else {
throw($e);
}
}
}
However, the catch block does not work. The stack trace shows me the error happened at the line doSomeNastyStuff(). Where is the problem?
The problem is, you are rethrowing your Exception. The stack trace is part of the Exception instance and is recorded at the moment, exception is created. You can get the stack trace by
$e->getTrace(); // Exception $e
When you rethrow exception in your code, it still has the old stack trace recorded and this tricks your framework to show you, the exception actually happened at the line doSomeNastyStuff() and it seems like the catch does not work.
Therefore, it is better idea to rethrow exceptions the following way:
/** instead of throw($e) do */
throw new \Exception("Unhandled exception", 1, $e);
Beginining with php5.3, Exception constructor has optional third parameter $previous exactly for this purpose. You can then get the previous Exception using $e->getPrevious();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With