Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

c# - Exceptions: When to use, timing, overall use

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

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;
}

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

First chance System.FormatException blabla

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

I recommend Eric Lippers's blog entry: Vexing exceptions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...