我应该如何经常使用尝试和catch在C#中? [英] How often should I use try and catch in C#?
问题描述
在编写C#应用程序,它的首要任务是永不死机中,我应该怎么经常使用try-catch块?
When writing a C# application whose #1 priority is to never crash, how often should I used a try-catch block?
我可以封装在一个方法中的所有语句的try-catch块?
Can I encapsulate all the statements in a method in try-catch blocks?
public void SomeMethod()
{
try
{
// entire contents of the function
// library calls
// function calls
// variable initialization .. etc
}
catch (Exception e)
{
// recover
}
}
什么缺点在包装的try-catch块的一切吗?
What are the downsides to wrapping everything in try-catch blocks?
推荐答案
唯一的缺点是,当一个异常被抛出实际。没有开销包裹code,除非发生异常时。
The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.
此外,你不希望使用try / catch语句的控制流。考虑这个(坏code):
Also, you don't want to use try/catch for control flow. Consider this (bad code):
try {
FileStream fs = File.Open("somefile.txt", FileMode.Open);
} catch (Exception ex) {
MessageBox.Show("The file does not exist. Please select another file");
}
您会得到像从一些File.Exists更多的东西表现。如:
You'll get more performance from some thing like File.Exists. such as:
if(!File.Exists("somefile.txt"))
MessageBox.Show("The file does not exist.")
编辑:
发现 MSDN直接引用:
查找和设计走
异常沉重code可能导致
体面PERF取胜。请记住,
这有没有关系的try / catch
块:你只收取成本时,
实际的异常。您
可以使用尽可能多的try / catch块作为
你要。使用异常
无偿为你失去
性能。例如,您应该
远离的东西收起来就像使用
例外的控制流程。
Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.
这篇关于我应该如何经常使用尝试和catch在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!