Back to notes -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    A C# program with a handled exception.Lecture 9 - slide 18 : 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;

    M(table, idx);
  }

  public static void M(int[] table, int idx){
    try{                                                       
      Console.WriteLine("Accessing element {0}: {1}", 
                         idx, table[idx]);
      Console.WriteLine("Accessing element {0}: {1}", 
                         idx-1, table[idx-1]);
    } 
    catch (IndexOutOfRangeException e){                        
      int newIdx = AdjustIndex(idx,0,5);                       
      Console.WriteLine("We get element number {0}: {1}",      
                         newIdx, table[newIdx]);            
    }   
    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;
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
In a try-catch statement ...
 
 
 
 
 
... we handle the error in the 
neighborhood of the place where
the error occurs.
 
 
 
 
 
 
 
The static method that enforces i
to be within the range low..high.