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 } }
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.
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.
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.
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.
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(); } } }
After answering this question, I wrote a more in depth post about the IDisposable and Using construct in my blog.
Yes. A using
statement translates to approximately the following construct:
IDisposable x; try { ... } finally { x.Dispose(); }
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