我为什么要在php中使用异常处理?
发布时间:2020-12-13 18:10:24 所属栏目:PHP教程 来源:网络整理
导读:我已经编程了很长一段时间的 PHP,但没有那么多 PHP 5 …我已经知道PHP 5中的异常处理了一段时间,但从未真正研究过它.在使用快速Google之后,使用异常处理似乎毫无意义 – 我无法看到使用它而不仅仅使用一些if(){}语句,以及可能是我自己的错误处理类或其他什么
我已经编程了很长一段时间的
PHP,但没有那么多
PHP 5 …我已经知道PHP 5中的异常处理了一段时间,但从未真正研究过它.在使用快速Google之后,使用异常处理似乎毫无意义 – 我无法看到使用它而不仅仅使用一些if(){}语句,以及可能是我自己的错误处理类或其他什么的优点.
使用它必须有很多充分的理由(我猜?!)否则它不会被放入语言(可能).有人能告诉我它只是使用一堆if语句或switch语句或其他什么好处吗?
例外允许您区分不同类型的错误,并且也非常适合路由.例如…
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; } } } 然后,可以通过自定义错误处理程序处理抛出的异常. 由于PHP是一种松散类型的语言,因此您可能需要确保只将字符串作为参数传递给类方法.例如… class StringsOnly { public function onlyPassStringToThisMethod($string) { if (!is_string($string)) { throw new InvalidArgumentException('$string is definitely not a string'); } // Cool string manipulation... return $this; } } …或者如果您需要以不同方式处理不同类型的异常. 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) { // Get DB debug info $this->logDbDebugInfo(); return 'Could not access database. What did you mess up this time?'; } catch (Exception $e) { $this->logMiscException($e); return 'I catch all exceptions for which you did not account!'; } } } 如果在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) { // Error encountered,rollback changes $this->getDb()->rollBack(); // Re-throw exception,allow ErrorController forward throw $e; } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |