Reputation: 39615
I'm trying to write a Dispose
method which has the potentian to throw an exception.
The dispose is invoked in a try-finally
pattern, via a using
statement:
using(var widget = new Widget())
{
widget.DoYourThing();
}
The problem is that if an exception is raised by the Dispose
method, it replaces any exception which may have been raised during the body of the using
block. Typically this exception is less-useful than the one thrown in the body.
What I would like is to write the Dispose
method in such a way that it swallows its own exceptions if there is an exception already in progress. Something like the following would be ideal:
protected virtual void Dispose(bool disposing)
{
try
{
this.Shutdown();
}
catch(Exception)
{
this.Abort();
// Rethrow the exception if there is not one already in progress.
if(!Runtime.IsHandlingException)
{
throw;
}
}
}
Is there anything which can provide this information?
Upvotes: 6
Views: 414
Reputation: 4014
Is it truly necessary for your Dispose
method to be able to throw an exception?
Perhaps you should create another disposal method with a different name, and have that throw an exception if necessary. Then implement Dispose
by calling that other method, wrapped in a try
block that will swallow the exception so that Dispose
never throws.
Upvotes: 1
Reputation: 26717
have a look at the below:
http://msdn.microsoft.com/en-us/library/aa355056.aspx
Upvotes: 0