Back to notes -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    A C# program with simple propagation of exception handling.Lecture 9 - slide 22 : 30
Program 1
using System;

class ExceptionDemo{

  public static void Main(){
    int[] table = new int[6]{10,11,12,13,14,15};
    int idx = 6;

    try{                                                     
      M(table, idx);                                         
    }   
    catch (IndexOutOfRangeException){                        
      int newIdx = AdjustIndex(idx,0,5);
      M(table, newIdx);                                      
    }
    Console.WriteLine("End of Main"); 
  }

  public static void M(int[] table, int idx){
    try{                                                    
      Console.WriteLine("Accessing element {0}: {1}",       
                         idx, table[idx]);                  
    }                                                       
    catch (NullReferenceException){
      Console.WriteLine("A null reference exception");
      throw;      // rethrowing the exception
    }   
    catch (DivideByZeroException){
      Console.WriteLine("Dividing by zero");
      throw;     // rethrowing the exception
    }

    Console.WriteLine("End of M"); 
  }



  public static int AdjustIndex(int i, int low, int high){  
    int res;
    if (i < low)
      res = low;
    else if (i > high)
      res = high;
    else res = i;

    return res;
  }
}
 
 
 
 
 
 
 
 
A try-catch statement in the 
context of the call of M.
 
Handles the error which occurs.
 
Calls M with adjusted index.
 
 
 
 
 
A try catch statement in the context
of the 'point of the error'.
In vain. The error is propagated to
to Main.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
The usual AdjustIndex method.