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
Exceptioninstance and is recorded at the moment, exception is created. You can get the stack trace byWhen 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 thecatchdoes not work.Therefore, it is better idea to rethrow exceptions the following way:
Beginining with php5.3,
Exception constructorhas optional third parameter$previousexactly for this purpose. You can then get the previousExceptionusing$e->getPrevious();