Try/Catch block in PHP not catching Exception

Solution 1:

I just had this exact problem where it seemed like I had even copied the name of the exception and yet it didn't catch it. It turned out it was my stupid mistake but I thought I should post my case here in case there is someone else in the same situation.

I had my exception in my namespace called A and the script was in a namespace called B. The problem was that I had A\MyException which equals (in PHP) \B\A\MyException (because my script is in the namespace called B!). All I had to do to fix it was to add backslash (or whatever it's called) to the exception name so it would look like this: \A\MyException

Solution 2:

Quite old question, yet...

I had this problem as well (and that's how I found this post) but just simple experiment allowed me to find the solution. Just try changing Exception to \Exception. Worked for me!

EDIT:

As sivann pointed in the comments, using namespace should do the same thing. So simply put use \Exception as Exception; before your class declaration.

Solution 3:

Try to put catch(\Exception $e) instead of catch(Exception $e) . If you are using a code you don't know about very well, or - especially - if you are using a framework, it might override the default PHP Exception with one of its own, and therefore you might go to the wrong path and get the undesired result. If you just put \Exception , then you are sure you are catching the base PHP exception.