我在哪里放置 try/catch 和“使用"?陈述? [英] Where do I put try/catch with "using" statement?

查看:33
本文介绍了我在哪里放置 try/catch 和“使用"?陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
try/catch + using,正确的语法

我想try/catch以下内容:

//write to file
using (StreamWriter sw = File.AppendText(filePath))
{
    sw.WriteLine(message);
}

我是将 try/catch 块放在 using 语句中,还是放在它的周围,或者两者兼而有之?

Do I put the try/catch blocks inside the using statement, or around it, or both?

推荐答案

如果你的 catch 语句需要访问 using 语句中声明的变量,那么 inside 是你唯一的选择.

If your catch statement needs to access the variable declared in a using statement, then inside is your only option.

如果您的 catch 语句在处理之前需要 using 中引用的对象,那么 inside 是您唯一的选择.

If your catch statement needs the object referenced in the using before it is disposed, then inside is your only option.

如果您的 catch 语句执行未知持续时间的操作,例如向用户显示消息,并且您希望在此之前处理您的资源,那么外部是您的最佳选择.

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.

每当我遇到与此类似的场景时,try-catch 块通常采用不同的方法,从 using 调用堆栈进一步向上.一个方法知道如何处理在它内部发生的异常是不典型的.

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.

private void saveButton_Click(object sender, EventArgs args)
{
    try
    {
        SaveFile(myFile); // The using statement will appear somewhere in here.
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

这篇关于我在哪里放置 try/catch 和“使用"?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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