Sample Program - Exception Handling


//  this program creates an array with 10 elements, then generates randomly
//  generates subscripts between 0 and 20 inside a try block. the 
//  catch prints an error message if the subscript is out of range

public class ExcepCont {
   public static void main(String[] args) {
      int[] nums = new int[10];
      int j = 0;
      for (int i = 0 ; i < 10 ; i++)
         nums[i] = 3 * i + 2;

//  generate 10 random subscripts; errors will be handled by catch block

      for (int k = 0 ; k < 10 ; k++) {
         try {
            j = (int) Math.round(20 * Math.random());
            nums[j] = j;
            System.out.println("Replaced value of nums[" + j + "]");
         } //  end try

//  first catch will handle invalid subscripts, second catch will handle
//  any other errors

         catch(ArrayIndexOutOfBoundsException out) {
            System.out.println("Index generated (" + j + ") was out of bounds");
         }
         catch(Exception e) {
            System.out.println("Exception occurred of type " + e);
         }
      } //  end for
      System.out.println("End of main");
   }
}

Output:
Index generated (16) was out of bounds
Index generated (14) was out of bounds
Replaced value of nums[5]
Replaced value of nums[3]
Index generated (13) was out of bounds
Index generated (15) was out of bounds
Replaced value of nums[5]
Index generated (13) was out of bounds
Replaced value of nums[4]
Index generated (18) was out of bounds
End of main

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page