Where can I put try / catch with the using statement?

Possible duplicate:
try / catch + using, correct syntax

I would like to try/catch following:

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

Am I placing try/catch blocks inside or around a using statement? Or both?

+13
c # try-catch using-statement
May 26 '11 at 21:21
source share
3 answers

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

If your catch statement needs an object referenced by usage before it is deleted, then your only option.

If your catch statement takes an action of unknown duration, for example, displaying a message to the user, and you would like to get rid of your resources before this happens, then the external option is your best option.

Whenever I have a scenerio like this, the try-catch block is usually located in another method, located further from the call stack from use. It is not typical for a method to know how to handle exceptions that occur inside it like this.

So my general recommendation goes out.

 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); } } 
+25
May 26 '11 at 21:29
source share

I assume this is the preferred way:

 try { using (StreamWriter sw = File.AppendText(filePath)) { sw.WriteLine(message); } } catch(Exception ex) { // Handle exception } 
+8
May 26, '11 at 21:23
source share

If you need a try / catch block, then using does not buy you much. Just drop it and do it instead:

 StreamWriter sw = null; try { sw = File.AppendText(filePath); sw.WriteLine(message); } catch(Exception) { } finally { if (sw != null) sw.Dispose(); } 
+4
May 26 '11 at 21:27
source share



All Articles