C#中嵌套的try Catch语句或方法? [英] C# Nested Try Catch statements or methods?

查看:1177
本文介绍了C#中嵌套的try Catch语句或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的最佳实践的问题。

Simple best practice question.

你是否应该巢尝试catch语句或者只是使用的方法。

Should you nest try catch statements or just use methods.

有关举例来说,如果你有打开一个文件不工作并关闭该文件的方法,你就必须打开和关闭的尝试捕捉之外,或者说接近finally块。

For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.

现在,如果你的开放的方法失败,则该方法会断言吧?所以,如果您的包裹,在一个try catch块或者应该是从另一种方法,称为这反过来又为try catch块?

Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?

推荐答案

在打开一个文件,我会用using语句VS一试捕的方法的情况下。 using语句确保如果发生异常调用Dispose。

In the context of a method that opens a file I would use a using statement vs a try catch. The using statement ensures that Dispose is called if an exception occurs.

using (FileStream fs = new FileStream(file, FileMode.Open))
{
    //do stuff
}

做同样的事情:

FileStream fs;
try
{
     fs = new FileStream(file, FileMode.Open);
     //do Stuff
 }
 finally
 {
        if(fs!=null)
           fs.Dispose();
 }

这篇关于C#中嵌套的try Catch语句或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆