微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我为什么要在php中使用异常处理?

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

原文地址:https://www.jb51.cc/php/134825.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐