Where do I put try/catch with "using" statement?

Ryan R picture Ryan R · May 26, 2011 · Viewed 42.2k times · Source

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?

Answer

Jeffrey L Whitledge picture Jeffrey L Whitledge · May 26, 2011

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