In the IDisposable.Dispose
method is there a way to figure out if an exception is being thrown?
using (MyWrapper wrapper = new MyWrapper()) { throw new Exception("Bad error."); }
If an exception is thrown in the using
statement I want to know about it when the IDisposable
object is disposed.
IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.
Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up.
The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
You can extend IDisposable
with method Complete
and use pattern like that:
using (MyWrapper wrapper = new MyWrapper()) { throw new Exception("Bad error."); wrapper.Complete(); }
If an exception is thrown inside the using
statement Complete
will not be called before Dispose
.
If you want to know what exact exception is thrown, then subscribe on AppDomain.CurrentDomain.FirstChanceException
event and store last thrown exception in ThreadLocal<Exception>
variable.
Such pattern implemented in TransactionScope
class.
No, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause.
See this post on my blog, for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with the IDisposable pattern.
Ayende has a trick that will allow you to detect an exception happened, however, it will not tell you which exception it was.
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