catch块与在方法中引发新Exception之间的区别 [英] Difference between catch block and throw new Exception in method

查看:132
本文介绍了catch块与在方法中引发新Exception之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种方法中,我希望能够在div中插入一个值,该div是我选择解析的html文档的一部分。

In a method, I want to be able to insert a value into a div which is part of the html document I choose to parse.

public void AddToDiv(string div)
{
    //Code to read the html document and look for the div 
    //(name specified as the parameter of this method).
} 

问题是,我可以指定一个名为 abc的div,但是html文档可能没有这个div。足够公平,但是我说的有什么区别:

Question is, I could specify a div called "abc" but the html document may not have this div. Fair enough, but what is the difference between me saying:

try
{
    //Method logic to parse document for the div
}
catch(ArgumentException ex)
{
    // (I wouldn't supress this catch block in production code, 
    // just omitting body details for simplicity.
}

OR

public void ParseDocument
{
    //Logic here...

    if(!document.Contains(div)
    {
    throw new ArgumentException();
    }
}

简而言之,catch块与在主逻辑块中说出新的[ExceptionType here]之间有什么区别?我该如何决定使用哪个?

In short, what is the difference between a catch block and saying throw new [ExceptionType here] in the main logic block? How do I decide which is to use?

谢谢

推荐答案

我个人要检查是否存在,而不是允许抛出异常,它是更容易确定逻辑流,并且更适合您的代码意图。

Personally, I'd check for existence, rather than allowing the exception to be thrown, it's easier to determine the flow of logic, and fits better with the intent of your code.

请参阅以下问答以进行更广泛的讨论

See these questions and answers for a broader discussion

何时引发异常

是否有任何有效的理由可以忽略捕获的异常

.net异常的速度有多慢?

编辑:

再三考虑,您应该考虑包含检查的费用。如果它可能与实际获得div一样昂贵,并且它使例程运行所花费的时间加倍,并且如果这种滞后将性能降低到可以引起注意的程度,那么可能是最好只是去获得股利。我仍然会抓住它并抛出ArgumentException,并将原始异常作为内部异常。

On second thoughts, you should consider the expense of the "containts" check. If it's likely to be as expensive as actually getting the div, and it's doubling the time it takes the routine to run and if this lag degrades performance to the point where it'll be noticed, then possibly it's better to just go and get the div. I'd still catch it and throw the ArgumentException, with the original exception as the inner exception.

注意:需要。

这篇关于catch块与在方法中引发新Exception之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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