illustrates a nested try/catch block

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example13_5.cs illustrates a nested try/catch block;
  the nested if throws an exception that is propagated to the
  outer exception
*/

using System;

public class Example13_5
{

  public static void Main()
  {

    try
    {

      // a nested try and catch block
      try
      {

        int[] myArray = new int[2];
        Console.WriteLine("Attempting to access an invalid array element");
        myArray[2] = 1;  // throws the exception

      }
      catch (DivideByZeroException e)
      {

        // code that handles a DivideByZeroException
        Console.WriteLine("Handling a DivideByZeroException");
        Console.WriteLine("Message = " + e.Message);
        Console.WriteLine("StackTrace = " + e.StackTrace);

      }

    }
    catch (IndexOutOfRangeException e)
    {

      // code that handles an IndexOutOfRangeException
      Console.WriteLine("Handling an IndexOutOfRangeException");
      Console.WriteLine("Message = " + e.Message);
      Console.WriteLine("StackTrace = " + e.StackTrace);

    }

  }

}