Joh*_*unt 8 php exception-handling
我已经编程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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以通过自定义错误处理程序处理抛出的异常.
由于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;
}
}
Run Code Online (Sandbox Code Playgroud)
...或者如果您需要以不同方式处理不同类型的异常.
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!';
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2832 次 |
| 最近记录: |