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. ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.