我会试着问我的问题,这样它就不会以一个简单的争论话题结束。
我最近跳进了一个用 C# 编码的应用程序,我发现了异常机制。我和他们有过一些不好的经历,比如以下
// _sValue is a string
try
{
return float.Parse(_sValue);
}
catch
{
return 0;
}
我把它改成:
float l_fParsedValue = 0.0f;
if (float.TryParse(_sValue, out l_fParsedValue))
{
return l_fParsedValue;
}
else
{
return 0;
}
结果,我在 Visual Studio 中的输出不再充斥着类似的消息
第一次机会 System.FormatException blabla
当像'-'这样的字符串到达片段时。我认为使用第二个片段更清洁。
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".
Thanks in advance for your help!