当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Try-Catch Exception abuse

问题描述:

I have found some code like this:

try

{

myClass.do().ToString();

} catch () { }

which certainly results in an exception being thrown when do() returns null. You could, instead, use

(myClass.do() ?? "").ToString();

to avoid the exception being thrown. I also see code like this:

for (int i = 0; i < x.length; i++)

{

if (x.Phases[i].num == activeNum)

{

try

{

result = x.Phases[i + 1].obj;

}

catch (Exception ex) { }

}

}

I think that this is not good practice. However, I can't find any references to support my ideas.

I tried to search on web, but I did not have any luck. Most of the references or documentation was meant for C++ or Java.

Will you please help me to justify my idea with strong reference, or enlighten me if the previous approaches above are in fact acceptable.

网友答案:

You're correct: using exceptions for purposes of flow control is generally bad practice. It is often referred to as an anti-pattern for this reason.

You can find a detailed explanation here. While the article references Java and C++, it is also an anti-pattern in C# for much the same reasons.

For a C#/.Net specific explanation, see this MSDN article.

网友答案:

Your intuition is right. Exception handling is slow.

Branching (such as an underlying jump when the for-loop terminates) is very fast.

Don't waste your time on exception handling as a means of flow control.

分享给朋友:
您可能感兴趣的文章:
随机阅读: