我已经编程了很长一段时间的
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;
}
}
}