3

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?

1 Answer 1

5

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();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.