Google


   


You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Exception Handling > Assuring Exceptions Are Not Lost When Using Finally Blocks

SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

Recipe 7.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 throw an exception, it is possible that the thrown exception will get discarded and that a new and unexpected exception will 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 ThrowException method, as is instigated by the code shown in Example 7-1.

Example 7-1. Throwing an error from the inner finally block of the ThrowExceptionMethod

private void ThrowException( )
{
    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 e)
    {
        Console.WriteLine("Another type of error occurred. " +
                          "Error message == " + e.Message);
        throw;
    }
    finally
    {
        try
        {
            Console.WriteLine("In inner finally");
            throw(new Exception("Oops"));
        }
        catch(Exception e)
        {
            Console.WriteLine(@"An error occurred in the finally block. " +
                               "Error message == " + e.Message);
        }
    }
}
public void PreventLossOfException( )
{
    try
    {
        Console.WriteLine("In outer try");
        ThrowException( );
    }
    catch(Exception e)
    {
        Console.WriteLine("In outer catch. ReThrown error == " + e.Message);
    }
    finally
    {
        Console.WriteLine("In outer finally");
    }
}

the following output would be displayed:

	In outer try
	In inner try
	An Overflow occurred. Error message == Arithmetic operation resulted in an
	overflow.
	In inner finally
	In outer catch. ReThrown error == Oops
	In outer finally

If you modify the inner finally block to handle its own errors (changes are highlighted), similarly to the following code:

	public void PreventLossOfException( )
	{
	    try
	    {
	        Console.WriteLine("In outer try");
	        ThrowException( );
	    }
	    catch(Exception e)
	    {
	        Console.WriteLine("In outer catch. ReThrown error == " + e.Message);
	    }
	    finally
	    {
	        Console.WriteLine("In outer finally");
	    }
	}

you will get the following output:

	In outer try
	In inner try
	An Overflow occurred. Error message == Arithmetic operation resulted in an
	overflow.
	In inner finally
	An error occurred in the finally block. Error message == Oops
	In outer catch. ReThrown error == Arithmetic operation resulted in an overflow.
	In outer finally

By handling exceptions within the inner finally block, you assure that the correct rethrown exception bubbles up to the outer exception handler.

When writing a finally block, consider placing a separate try-catch around the code.


See Also

See the "Error Raising and Handling Guidelines" topic and the "throw," "try," "catch," and "finally" keywords in the MSDN documentation.


SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Exception Handling > Assuring Exceptions Are Not Lost When Using Finally Blocks


ADBRITE ads links
   
Related tags







Popular Categories
Unix books and guides

AJAX popular information
C# language guides
Windows books and cookbooks

.......








Business Key Top Sites

be number one
rate your site




    С 2009 года мы стали переводить структура сайта на различные языки. Сайт теперь будет содержать книги не только на английском языке, но также и на других европейских языках, в том числе и на Русском языке.

    Русский Polski Francais Deutsch
    support sitemap terms

© CodeIdol Labs, 2007 - 2009