什么时候捕获异常? [英] When to catch exceptions?

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

问题描述

如果我在没有使用异常的情况下做下列操作,会有什么不同?

Would there be any difference If i do the following without using exceptions?

void func()
{
    try
    {
        if (n > 5)
        {
            throw "n is greater than 5";
        }
    }
    catch (const char *e)
    {
        MessageBox(0, e, 0, 0);
        return;
    }
}

void func()
{
    if (n > 5)
    {
       MessageBox(0, "n is greater than 5", "Error", 0);
       return;
    }
}


推荐答案

I可能会说,你最好建议不要使用流量控制的例外。例外,顾名思义,是用于处理特殊情况。在上述情况下,你明显期望n可能> 5,所以它不是一个特殊的情况。如果你的应用程序有办法处理这种情况,那么它应该这样做,而不是提出异常。

I would probably say that you best advised not to use exceptions for flow control. Exceptions, as the name suggests, are for handling exceptional circumstances. In the above case you're clearly expecting n to possibly be > 5 so it's not really an exceptional circumstance. If there is a way for your application to deal with that case, then it should do so in preference to raising an exception.

我确定有些情况下逻辑下降,但一般来说,我认为这是一个很好的经验法则。

I'm sure there are cases where that logic falls down but in general I think that's a good rule of thumb.

但在技术术语没有太大的区别(可能的性能,如果你做lot)。

But in technical terms there isn't much difference (possibly performance if you're doing it a lot).

这篇关于什么时候捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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