Exceptions allow you to distinguish between different types of errors, and are also great for routing. For example...
class Application { public function run() { try { // Start her up!! } catch (Exception $e) { // If Ajax request, send back status and message if ($this->getRequest()->isAjax()) { return Application_Json::encode(array( 'status' => 'error', 'msg' => $e->getMessage()); } // ...otherwise, just throw error throw $e; } } }
An abandoned exception can be handled by a special error handler.
Since PHP is a freely typed language, you may need to make sure that only strings are passed as arguments to the class method. For example...
class StringsOnly { public function onlyPassStringToThisMethod($string) { if (!is_string($string)) { throw new InvalidArgumentException('$string is definitely not a string'); }
... or if you need to handle different types of exceptions differently.
class DifferentExceptionsForDifferentFolks { public function catchMeIfYouCan() { try { $this->flyForFree(); } catch (CantFlyForFreeException $e) { $this->alertAuthorities(); return 'Sorry, you can\'t fly for free dude. It just don\'t work that way!'; } catch (DbException $e) {
If you use transactions in something like Zend Framework:
class CreditCardController extends Zend_Controller_Action { public function buyforgirlfriendAction() { try { $this->getDb()->beginTransaction(); $this->insertGift($giftName, $giftPrice, $giftWowFactor); $this->getDb()->commit(); } catch (Exception $e) {
webjawns.com
source share