Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 773
Ryan R Avatar asked May 26 '11 21:05

Ryan R


People also ask

Where do you put try-catch?

Put the try-catch where you are sure you won't just swallow the exception. Multiple try-catch blocks in various layers may be OK if you can ensure consistency. For example, you may put a try-catch in your data access layer to ensure you clean up connections properly.

Can we insert statements between try and catch?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Can we use try-catch in using in C#?

The try-catch statement in C# is used in exceptions in C#. The try block holds the suspected code that may get exceptions. When an exception is thrown, the . NET CLR checks the catch block and checks if the exception is handled.

Can you have 2 try-catch?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.


2 Answers

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);     } } 
like image 193
Jeffrey L Whitledge Avatar answered Sep 22 '22 02:09

Jeffrey L Whitledge


I suppose this is the preferred way:

try {     using (StreamWriter sw = File.AppendText(filePath))     {         sw.WriteLine(message);     } } catch(Exception ex) {    // Handle exception } 
like image 22
CD.. Avatar answered Sep 23 '22 02:09

CD..