我应该把 try/catch 和“using”放在哪里?陈述?
可能的重复:
try/catch + 使用正确的语法
我想 try/catch
以下内容:
//write to file
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);
}
我是否将 try
/catch
块放置在 using
语句内、或周围,或两者都放置?
Possible Duplicate:
try/catch + using, right syntax
I would like to try/catch
the following:
//write to file
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);
}
Do I put the try
/catch
blocks inside the using
statement, or around it, or both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的 catch 语句需要访问 using 语句中声明的变量,那么 inside 是您唯一的选择。
如果您的 catch 语句需要在释放之前使用 using 中引用的对象,那么 inside 是您唯一的选择。
如果您的 catch 语句执行持续时间未知的操作(例如向用户显示消息),并且您希望在此之前处理掉您的资源,那么外部是您的最佳选择。
每当我遇到与此类似的场景时,try-catch 块通常位于调用堆栈中与 using 不同的方法中。像这样知道如何处理其中发生的异常的方法并不典型。
所以我的一般建议是在外面——远远的外面。
If your catch statement needs to access the variable declared in a using statement, then inside is your only option.
If your catch statement needs the object referenced in the using before it is disposed, then inside is your only option.
If your catch statement takes an action of unknown duration, like displaying a message to the user, and you would like to dispose of your resources before that happens, then outside is your best option.
Whenever I have a scenerio similar to this, the try-catch block is usually in a different method further up the call stack from the using. It is not typical for a method to know how to handle exceptions that occur within it like this.
So my general recomendation is outside—way outside.
我想这是首选方式:
I suppose this is the preferred way:
如果你无论如何都需要一个 try/catch 块,那么 using 语句不会给你带来太多好处。只需放弃它并执行以下操作即可:
If you need a try/catch block anyway then the using statement is not buying you much. Just ditch it and do this instead: