Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an Exception happens within a using statement does the object still get disposed?

If an Exception happens within a using statement does the object still get disposed?

The reason why I'm asking is because I'm trying to decide on whether to put a try caught around the whole code block or within the inner using statement. Bearing in mind certain exceptions are being re-thrown by design within the catch block.

using (SPSite spSite = new SPSite(url)) {    // Get the Web    using (SPWeb spWeb = spSite.OpenWeb())    {        // Exception occurs here    } } 
like image 867
Andrew Avatar asked Nov 29 '11 11:11

Andrew


People also ask

Does using dispose if exception?

MSDN using documentation also confirms this answer: The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

What if exception occurs in using block?

The exception is thrown, because there is no catch statement in the compiled code. If you handle the exception within the using block, your object will still be disposed in the compiler-generated finally block.

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 happens when you throw an exception in C#?

The Anatomy of C# Exceptions catch – When an exception occurs, the Catch block of code is executed. This is where you are able to handle the exception, log it, or ignore it. finally – The finally block allows you to execute certain code if an exception is thrown or not.


2 Answers

Yes, they will.

using(SPWeb spWeb = spSite.OpenWeb()) {   // Some Code } 

is equivalent to

{   SPWeb spWeb = spSite.OpenWeb();   try   {      // Some Code   }   finally   {     if (spWeb != null)     {        spWeb.Dispose();     }   } } 

Edit

After answering this question, I wrote a more in depth post about the IDisposable and Using construct in my blog.

like image 98
Anders Abel Avatar answered Sep 20 '22 19:09

Anders Abel


Yes. A using statement translates to approximately the following construct:

IDisposable x; try {     ... } finally {     x.Dispose(); } 
like image 28
spender Avatar answered Sep 21 '22 19:09

spender