What is the best practice in C# to propagate an exception thrown in a finally block without loosing an exception from a catch block?

Posted by Sergey Smolnikov on Stack Overflow See other posts from Stack Overflow or by Sergey Smolnikov
Published on 2013-10-20T15:51:28Z Indexed on 2013/10/20 15:53 UTC
Read the original article Hit count: 216

Filed under:

When an exception is possible to be thrown in a finally block how to propagate both exceptions - from catch and from finally?

As a possible solution - using an AggregateException:

internal class MyClass
{
    public void Do()
    {
        Exception exception = null;
        try
        {
            //example of an error occured in main logic
            throw new InvalidOperationException();
        }
        catch (Exception e)
        {
            exception = e;
            throw;
        }
        finally
        {
            try
            {
                //example of an error occured in finally
                throw new AccessViolationException();
            }
            catch (Exception e)
            {
                if (exception != null)
                    throw new AggregateException(exception, e);
                throw;
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#