gho*_*ost 17 c# methods error-handling
简单的最佳实践问题.
你应该嵌套try catch语句还是只使用方法.
例如,如果您有一个打开文件的方法可以正常工作并关闭文件,那么您可以在try catch外部打开和关闭,或者在finally块中关闭.
现在,如果你的open方法失败了,那么该方法会断言吗?那么你应该在try catch块中包装它还是应该从另一个方法中调用它,而另一个方法又是一个try catch块?
cgr*_*eno 15
在打开文件的方法的上下文中,我将使用using语句与try catch.using语句确保在发生异常时调用Dispose.
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
做同样的事情:
FileStream fs;
try
{
fs = new FileStream(file, FileMode.Open);
//do Stuff
}
finally
{
if(fs!=null)
fs.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ers 11
既然我们有lambdas和类型推断以及其他一些东西,那么在其他语言中有一个常用的习惯用法现在在C#中很有意义.您的示例是关于打开文件,对其执行某些操作,然后关闭它.那么,现在,你可以创建一个打开文件的辅助方法,并且还要确保关闭/处理/清理,但是调用你为"do stuff"部分提供的lambda.这将帮助您在一个地方获得复杂的try/catch/finally dispose/cleanup,然后一遍又一遍地使用它.
这是一个例子:
public static void ProcessFile(string filePath, Action<File> fileProcessor)
{
File openFile = null;
try
{
openFile = File.Open(filePath); // I'm making this up ... point is you are acquiring a resource that needs to be cleaned up after.
fileProcessor(openFile);
}
finally
{
openFile.Close(); // Or dispose, or whatever.
}
}
Run Code Online (Sandbox Code Playgroud)
现在,此方法的调用者不必担心如何打开文件或关闭/处置它.他们可以这样做:
Helpers.ProcessFile("C://somefile.txt", f =>
{
while(var text = f.ReadLine())
{
Console.WriteLine(text);
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个样式问题,但对我来说,我尝试在单个方法中永远不会有多个try/catch/finally嵌套级别.在您进行嵌套尝试时,您几乎肯定违反了1 function = 1操作主体,并且应该使用第二种方法.
取决于您想要做什么,但在大多数情况下,嵌套的 try/catch 是函数过于复杂的标志(或者不太了解异常如何工作的程序员!)。
在打开文件的情况下,我将使用 IDisposable 持有者和 using 子句,因此放弃任何显式 try/catch 的需要。
归档时间: |
|
查看次数: |
44303 次 |
最近记录: |