Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am unable to catch exception in php code

Tags:

exception

php

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?

like image 561
Samuel Hapak Avatar asked Nov 28 '25 04:11

Samuel Hapak


1 Answers

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

like image 104
Samuel Hapak Avatar answered Nov 30 '25 17:11

Samuel Hapak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!