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.
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.
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.
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.
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 .
No, that looks perfectly fine. Your bar instance will be disposed before you even get into the catch block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With