Where do I put try/catch with “using” statement? [duplicate]

只谈情不闲聊 提交于 2019-12-20 11:18:07

问题


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?


回答1:


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.

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);
    }
}



回答2:


I suppose this is the preferred way:

try
{
    using (StreamWriter sw = File.AppendText(filePath))
    {
        sw.WriteLine(message);
    }
}
catch(Exception ex)
{
   // Handle exception
}



回答3:


If you need a try/catch block anyway then the using statement is not buying you much. Just ditch it and do this instead:

StreamWriter sw = null;
try
{
    sw = File.AppendText(filePath);
    sw.WriteLine(message);
}
catch(Exception)
{
}
finally
{
    if (sw != null)
        sw.Dispose();
}


来源:https://stackoverflow.com/questions/6145245/where-do-i-put-try-catch-with-using-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!