If your code has a namespace, the catch block must reference \Exception - the backslash - if there is no backslash, then PHP will look for Exception in your current namespace. This is usually aborted, and the thrown exception is thrown by Xdebug.
The following code passes the exception to Xdebug:
namespace foo; try { new \PDO(0); } catch (Exception $e) { echo "Caught!"; }
Adding a backslash before an Exception will look for (and find) Exception in the global namespace:
namespace foo; try { new \PDO(0); } catch (\Exception $e) { echo "Caught!"; }
Manually throwing exceptions can be confusing (which is why I used PDO above). If we try to throw an exception from the current namespace, PHP says that Exception does not exist there:
namespace foo; try { throw new Exception(); } catch (Exception $e) { echo "Caught!"; }
Throwing a global exception without a global reference in the catch block happens differently:
namespace foo; try { throw new \Exception(); // global Exception } catch (Exception $e) { echo "Caught!"; } // Fatal error: Uncaught exception 'Exception' in...
In light of all this, it's probably a good idea to always catch the catch Exception with a backslash.
namespace foo; try { throw new \Exception(); } catch (\Exception $e) { echo "Caught!"; }
joemaller
source share