O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.5. Assuring Exceptions are Not Lost when Using Finally Blocks

Problem

You have multiple nested try/catch, try/finally, and try/catch/finally blocks. If a catch block attempts to rethrow an exception, it is possible that the rethrown exception could get discarded and a new and unexpected exception could be caught by an outer exception handler. You want to prevent this situation from occurring.

Solution

Add an inner try/catch block in the finally block of the outer exception handler:

private void PreventLossOfException( )
{
    try
    {
        //...  
    }
    catch(Exception e)
    {
        Console.WriteLine("Error message == " + e.Message);
        throw;
    }
    finally
    {
        try
               {
               //...  
        }
               catch(Exception e)
               {
               Console.WriteLine(@"An unexpected error occurred in the finally block.   
                                Error message == " + e.Message);
               }
    }
}

This block will prevent the original exception from being lost.

Discussion

Consider what would happen if an error were thrown from the inner finally block contained in the ReThrowException method. If the code looked like this:

public void PreventLossOfException( ) { try { Console.WriteLine("In outer try"); ReThrowException( ); } catch(Exception e) { Console.WriteLine("In outer catch. ReThrown error == " + e.Message); } finally { Console.WriteLine("In outer finally"); } } private void ReThrowException( ) { try { Console.WriteLine("In inner try"); int z2 = 9999999; checked{z2 *= 999999999;} } catch(OverflowException ofe) { Console.WriteLine("An Overflow occurred. Error message == " + ofe.Message); throw; } catch(Exception ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required