Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect exception in finally block

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?

like image 270
Paul Turner Avatar asked Aug 26 '11 09:08

Paul Turner


1 Answers

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.

like image 93
Stuart Cook Avatar answered Sep 20 '22 16:09

Stuart Cook