例外:当使用,定时,整体使用 [英] Exceptions: When to use, timing, overall use

查看:194
本文介绍了例外:当使用,定时,整体使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会试着问我的问题,所以它不会结束,因为一个简单的议论主题。

I'll try and ask my question so it doesn't end as a simple argumentative thread.

最近我跳进一个应用程序codeD在C#中,我发现了异常机制。我也曾有过一些不好的经验,与他们如以下

I've jumped into an application coded in C# recently and I'm discovering the exception mechanism. And I've had a few bad experiences with them such as the following

// _sValue is a string
try
{
    return float.Parse(_sValue);
}
catch
{
    return 0;
}

我把它改为:

I changed it into :

float l_fParsedValue = 0.0f;
if (float.TryParse(_sValue, out l_fParsedValue))
{
    return l_fParsedValue;
}
else
{
    return 0;
}

结果,我在Visual Studio输出,不再被淹没的消息像

Result, my Output in Visual Studio is not anymore flooded with message like

第一次有机会System.FormatException布拉布拉

First chance System.FormatException blabla

在串像 - 到达的片段。我认为这是更清洁的使用第二个片段。

when string like '-' arrive in the snippet. I think it's cleaner to use the second snippet.

再进一步​​,我常常看到异常往往使用ILKE:我做任何我想在这个的try-catch,如果有什么不顺心,抓

Going a step further, I've often seen that exceptions are too often used ilke: "I do whatever I want in this try-catch, if anything goes wrong, catch.".

现在为了不卡住不良误解,我希望你们帮我清楚地定义如何/何时使用这些例外,当坚持与老同学如果......别人。

Now in order to not get stuck with bad misconceptions, I would like you guys to help me clearly define how/when to use those exceptions and when to stick with old school "if...else".

在此先感谢您的帮助!

推荐答案

您应该在特殊情况下,抛出异常。即当某种意外情况。如果你希望一个函数定期抛出一个异常,这是最容易坏的设计。

You should throw exception in exceptional cases. i.e. when something unexpected happens. If you expect a function to regularly throw an exception that's most likely bad design.

在你的例子是很清楚,的TryParse 是更好,因为例外似乎经常occor。

In your examples it is very clear that TryParse is better since the exception seems to occor often.

不过,分析文件时,例如,我希望它是几乎总是有效的。所以我通常使用解析和捕获异常,并生成一个 InvalidDataException 与捕获异常的内部异常。通常简化了解析codeA很多,即使它可能是坏的风格。

But for example when parsing a file, I expect it to be almost always valid. So I usually use Parse and catch the exception and generate a InvalidDataException with the caught exception as inner exception. Usually simplifies the parsing code a lot, even if it may be bad style.

我建议埃里克Lippers的博客文章:令人烦恼例外

I recommend Eric Lippers's blog entry: Vexing exceptions

这篇关于例外:当使用,定时,整体使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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