illustrates multiple catch blocks : Exception Try Catch « Language Basics « C# / C Sharp






illustrates multiple catch blocks

illustrates multiple catch blocks
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example13_4.cs illustrates multiple catch blocks
*/

using System;

public class Example13_4
{

  public static void Main()
  {

    try
    {

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

    }
    catch (DivideByZeroException e)
    {

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

    }
    catch (IndexOutOfRangeException e)
    {

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

    }
    catch (Exception e)
    {

      // code that handles a generic Exception: all other exceptions
      Console.WriteLine("Handling a System.Exception object");
      Console.WriteLine("Message = " + e.Message);
      Console.WriteLine("StackTrace = " + e.StackTrace);

    }

  }

}


           
       








Related examples in the same category

1.Catch Error
2.illustrates an unhandled exceptionillustrates an unhandled exception
3.illustrates how to handle a specific exceptionillustrates how to handle a specific exception
4.illustrates a nested try/catch blockillustrates a nested try/catch block
5.illustrates exception propagation with methodsillustrates exception propagation with methods
6.Catch Divide By Zero ExceptionCatch Divide By Zero Exception
7.Demonstrates stacking catch blocks to provide alternate code for more than one exception type
8.Catches an exception that was thrown in a component
9.Throw a format exception purposely to demonstrate catching a FormatException
10.Demonstrates using if statements to sort out an IOException
11.Several catch branchesSeveral catch branches
12.Demonstrate exception handlingDemonstrate exception handling
13.An exception can be generated by one method and caught by anotherAn exception can be generated by one 
   method and caught by another
14.Exception Type MismatchException Type Mismatch
15.Handle error gracefully and continueHandle error gracefully and continue
16.Use multiple catch statementsUse multiple catch statements
17.Use the 'catch all' catch statementUse the 'catch all' catch statement
18.Use a nested try blockUse a nested try block
19.Catch different exceptions
20.Passing Exceptions on to the Caller: Caller Confuse
21.Passing Exceptions on to the Caller: Caller Inform
22.Exception Handling:Trying and CatchingException Handling:Trying and Catching