C Sharp

Design Issues with the catch Block

The only code that should appear in a catch block is code that will at least partially process the caught exception. For example, at times a method will catch an exception, do what it can to process that exception, and then rethrow that exception so that further error handling can occur. The following example illustrates this. Foo has called Bar, which will do some database work on Foo 's behalf. Because commitment control, or transactions, are being used, Bar needs to catch any error that occurs and rollback the uncommitted changes before rethrowing the exception back to Foo.

using System;
class WhenToCatchApp
{
    public void Foo()
    {
        try
        {
            Bar();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    public void Bar()
    {
        try
        {
            // Call method to set a "commitment boundary."
            Console.WriteLine("setting commitment boundary");
            // Call Baz to save data.
            Console.WriteLine("calling Baz to save data");
            Baz();
            Console.WriteLine("commiting saved data");
        }
        catch(Exception)
        {
                // In this case, Bar should catch the exception
                // because it's doing something significant
                //(rolling back uncommitted database changes).
                Console.WriteLine("rolling back uncommited changes " +
                         "and then rethrowing exception");
            throw;
        }
    }
    public void Baz()
    {
        throw new Exception("db failure in Baz");
    }
    public static void Main()
    {
        WhenToCatchApp test = new WhenToCatchApp();
        test.Foo(); // This method will ultimately print
                    // the error msg.
    }
}

Bar needed to catch the exception to do its own error processing. When finished, it then rethrew the exception back up the call stack, where Foo caught it and was able to do its error processing. This ability of each level of the call stack to do just the amount of error processing that it's capable of, given its context, is one example of what makes exception handling so important to the design of your system.

Summary

The C# exception-handling syntax is simple and straightforward, and implementing exception handling in your applications is as easy as designing your methods ahead of time. A primary goal of the .NET CLR is to help prevent run-time errors through a strong type system and to handle gracefully any run-time errors that do occur. The use of exception-handling code in your applications will make them more robust, dependable, and ultimately easier to maintain.

by BrainBellupdated
Advertisement: