What is the best practice in C # for propagating an exception that is thrown in a finally block without losing an exception from the catch block?

If an exception can be thrown in the finally block, how can both exceptions be thrown - from catch, and finally?

As a possible solution, use 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;
            }
        }
    }
}

These exceptions can be handled as in the following snippet:

private static void Main(string[] args)
{
    try
    {
        new MyClass().Do();
    }
    catch (AggregateException e)
    {
        foreach (var innerException in e.InnerExceptions)
            Console.Out.WriteLine("---- Error: {0}", innerException);
    }
    catch (Exception e)
    {
        Console.Out.WriteLine("---- Error: {0}", e);
    }

    Console.ReadKey();
}
+4
source share
1 answer

, " " . , , , . , ( "" , . , , - OutOfMemoryException, , , , boned: -)

finally try, , . , , , AggregateException . , , , ().

+3

All Articles