Team LiB   Previous Section   Next Section

18.6 Creating Dedicated catch Statements

So far, you've been working with generic catch statements only. You can create dedicated catch statements that handle only some exceptions and not others, based on the type of exception thrown. Example 18-4 illustrates how to specify which exception you'd like to handle.

Example 18-4. Three dedicated catch statements
using System;

namespace ExceptionHandling
{
   class Tester
   {

      public void Run()
      {
          try
          {
              double a = 5;
              double b = 0; 
              Console.WriteLine("Dividing {0} by {1}...",a,b);
              Console.WriteLine ("{0} / {1} = {2}",
                  a, b, DoDivide(a,b));
          }

              // most derived exception type first
          catch (System.DivideByZeroException)
          {
              Console.WriteLine(
                  "DivideByZeroException caught!");
          }

          catch (System.ArithmeticException)
          {
              Console.WriteLine(
                  "ArithmeticException caught!");
          }

              // generic exception type last
          catch
          {
              Console.WriteLine(
                  "Unknown exception caught");
          } 
      }

       // do the division if legal
       public double DoDivide(double a, double b)
       {
           if (b == 0)
               throw new System.DivideByZeroException();
           if (a == 0)
               throw new System.ArithmeticException();
           return a/b;
       }


       static void Main()
       {
           Console.WriteLine("Enter Main...");
           Tester t = new Tester();
           t.Run();
           Console.WriteLine("Exit Main...");           
       }


   }
}
Output:
Enter Main...
Dividing 5 by 0...
DivideByZeroException caught!
Exit Main...

In Example 18-4, the DoDivide() method does not let you divide zero by another number, nor does it let you divide a number by zero. If you try to divide by zero, it throws an instance of DivideByZeroException. If you try to divide zero by another number, there is no appropriate exception; dividing zero by another number is a legal mathematical operation and shouldn't throw an exception at all. However, for the sake of this example, assume you don't want to allow division of zero by any number; you will throw an ArithmeticException.

When the exception is thrown, the runtime examines each exception handler in the order in which they appear in the code and matches the first one it can. When you run this program with a=5 and b=7, the output is:

5 / 7 = 0.7142857142857143

As you'd expect, no exception is thrown. However, when you change the value of a to 0, the output is:

ArithmeticException caught!

The exception is thrown, and the runtime examines the first exception: DivideByZeroException. Because this does not match, it goes on to the next handler, ArithmeticException, which does match.

In a final pass through, suppose you change a to 7 and b to 0. This throws the DivideByZeroException.

You have to be particularly careful with the order of the catch statements in this case because the DivideByZeroException is derived from ArithmeticException. If you reverse the catch statements, the DivideByZeroException matches the ArithmeticException handler and the exception never gets to the DivideByZeroException handler. In fact, if their order is reversed, it is impossible for any exception to reach the DivideByZeroException handler. Then the compiler recognizes that the DivideByZeroException handler cannot be reached and reports a compile error!

Typically, a method catches every exception it can anticipate for the code it is running. However, it is possible to distribute your try/catch statements, catching some specific exceptions in one function and more generic exceptions in higher calling functions. Your design goals should dictate the exact design.

Assume you have a Method A that calls another Method B, which in turn calls Method C, which calls Method D, which then calls Method E. Method E is deep in your code, while methods B and A are higher up. If you anticipate that Method E might throw an exception, you should create a try/catch block deep in your code to catch that exception as close as possible to the place where the problem arises. You might also want to create more general exception handlers higher up in the code in case unanticipated exceptions slip by.

    Team LiB   Previous Section   Next Section