If you’re working in a PHP file that’s namespaced, and you’ve setup a simple try/catch
block like this
try
{
//do something that might throw an exception
}
catch(Exception $e)
{
echo "Caught you!";
}
You may be surprised when your program doesn’t catch the thrown exception. That’s because Exceptions are classes, and the Exception
class exists in the global namespace. That means you need to catch it with a leading backslash.
catch(Exception $e)
{
echo "Caught you!";
}
In java, the Exception
in front of the $e
is a type declaration. Since PHP doesn’t have type declarations, their borrowing of this syntax has led to many developers (i.e. me) to think of Exception $e
as magic boilerplate, instead of an actual type hint.
Not strictly Magento 2 related, but it seems worth mentioning since Magento 2 will be a lot of developer’s first deep dive into PHP namespaces.