为什么要在php中使用异常处理? [英] Why should I use exception handling in php?

查看:119
本文介绍了为什么要在php中使用异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对PHP进行了很长时间的编程,但对PHP 5的了解却不多。。。一段时间以来,我对PHP 5中的异常处理有所了解,但从未真正研究过。快速浏览完Google之后,使用异常处理似乎毫无意义-我看不出使用它比仅使用一些if(){}语句以及也许是我自己的错误处理类或其他类的优势。

I've been programming PHP for a long time, but not so much PHP 5... I've known about exception handling in PHP 5 for some time, but never really looked into it. After a quick Google it seems fairly pointless to use exception handling - I can't see the advantages of using it over just using some if() {} statements, and perhaps my own error handling class or whatever.

使用它有很多充分的理由(我猜?!),否则它就不会被放入语言中(可能)。谁能告诉我它比仅使用一堆if语句或switch语句或其他东西有什么好处?

There's got to be a bunch of good reasons for using it (I guess?!) otherwise it wouldn't have been put into the language (probably). Can anyone tell me of some good benefits it has over just using a bunch of if statements or a switch statement or something?

推荐答案

异常使您能够区分不同类型的错误,并且对于路由也非常有用。例如...

Exceptions allow you to distinguish between different types of errors, and is 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;
        }
    }
}

然后可以通过自定义错误处理程序处理抛出的异常。

The thrown exception can then be handled by a custom error handler.

自PHP是一种松散类型的语言,您可能需要确保仅将字符串作为参数传递给类方法,例如...

Since PHP is a loosely typed language, you might need to ensure that only strings are passed as arguments to a class method. For example...

class StringsOnly
{
    public function onlyPassStringToThisMethod($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentException('$string is definitely not a string');
        }

        // Cool string manipulation...

        return $this;
    }
}

...或者是否需要处理其他类型

...or if you need to handle different types of exceptions in different ways.

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框架:

If using 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) {
            // Error encountered, rollback changes
            $this->getDb()->rollBack();

            // Re-throw exception, allow ErrorController forward
            throw $e;
        }
    }
}

这篇关于为什么要在php中使用异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆