Silent failure to catch exceptions in PHP

Just a quick post to mention an annoying PHP gotcha and the solution. (I'm using PHP 5.5.)

If you write code that is not in the root namespace, and if you write a try-catch block, the catch block will never execute unless you write a use statement to bring the PHP Exception class in to scope.

In other words this code will never catch any exceptions and it will never generate an appropriate runtime error like "class Exception not found":

namespace MyApp;

try {
    // some stuff
}
catch ( Exception $e ) {
    // why is no one visiting me?  :(
}

But this code will:

namespace MyApp;

use Exception;

try {
    // some stuff
}
catch ( Exception $e ) {
    // It's like a revolving door in here!  :)
}

Justin Hellings

"Justin? Hell of a guy! We would have kept him but you know how it is. Genius like that is always restless ... Eh? ... Oh, him ... No, I thought you meant someone else."



comments powered by Disqus