PHP Namespaces and Exceptions
Thursday, May 31st, 2012 | Programming
Recently, I was trying to catch an exception that was raised when someone entered an invalid date string. Every time I tried it however, it would continue to throw the standard Symfony2 error information, rather than executing my catch block.
try {
$date = new \DateTime($str);
return $this->setDateOfWork($date);
} catch (Exception $e) {
return false;
}
After a good thirty minutes of being puzzled, we eventually worked out what it was – because we were working within a namespace, we needed to call the Exception object, which is after all just another object, from the global namespace.
try {
$date = new \DateTime($str);
return $this->setDateOfWork($date);
} catch (\Exception $e) {
return false;
}
This applies to any other types of Exceptions you’re trying to catch too – make sure you’re in the correct namespace!
Recently, I was trying to catch an exception that was raised when someone entered an invalid date string. Every time I tried it however, it would continue to throw the standard Symfony2 error information, rather than executing my catch block.
try { $date = new \DateTime($str); return $this->setDateOfWork($date); } catch (Exception $e) { return false; }
After a good thirty minutes of being puzzled, we eventually worked out what it was – because we were working within a namespace, we needed to call the Exception object, which is after all just another object, from the global namespace.
try { $date = new \DateTime($str); return $this->setDateOfWork($date); } catch (\Exception $e) { return false; }
This applies to any other types of Exceptions you’re trying to catch too – make sure you’re in the correct namespace!