Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any issues with using block for an IDisposable within a try catch block?

Tags:

c#

.net


The MSDN recommends putting any instantiation of classes that implement IDisposable into a using block. Or alternatively, if it is being instantiated within a try-catch block, then Dispose in Finally.

Are there any problems with using a using block within a try-catch block like so?

try
{
    using (Foo bar = new Foo())
    {
       bar.doStuff();
    }
}
catch (Exception e)
{
    //vomit e
}

Of course I can just call Dispose in a Finally block, but I'm a newbie to programming and I'm just curious to know if doing something like this is practically acceptable or if someone would smack me up the back of my head and yell at me that I'm Doing-It-Wrong™.

Or rather, I'm more interested in knowing why this would be wrong if it is.

like image 566
Garry Wong Avatar asked Oct 20 '14 16:10

Garry Wong


People also ask

When to use using block in c#?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.

Does using statement call Dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.

What exceptions Cannot be stopped in the catch block?

Any exception that is thrown by the jitter before your code can start running cannot be caught or reported. Failure to compile your Main() method is the common case, typically a FileNotFoundException.

Should you use try catch blocks?

Like some others have said, you want to use try-catch blocks around code that can throw an Exception AND code that you are prepared to deal with. Regarding your particular examples, File. Delete can throw a number of exceptions, for example, IOException , UnauthorizedAccessException .


2 Answers

No, that looks perfectly fine. Your bar instance will be disposed before you even get into the catch block.

like image 191
nvoigt Avatar answered Sep 28 '22 00:09

nvoigt


This is... drum roll... absolutely fine.

The only issue is that you shouldn't use catch (Exception), but catch the specific errors you're interested in (even if this is just an example), but that has no bearing on the using. In fact, the only reason why you would put the using outside the try block is because you want to continue doing something with bar that's unrelated to the code that failed -- otherwise, keeping the scope as small as possible is generally a good idea.

like image 33
Jeroen Mostert Avatar answered Sep 28 '22 02:09

Jeroen Mostert