Here is my solution: Notice the use of catch without specifying the type or name of the exception. The output of the program is here:using System;
class ExceptionDemo{
public static void Main(){
int[] table = new int[6]{10,11,12,13,14,15};
int idx = 6;
Console.WriteLine("Main");
try{
M(table, idx);
}
catch (IndexOutOfRangeException){
M(table, AdjustIndex(idx,0,5));
}
}
public static void M(int[] table, int idx){
Console.WriteLine("Calling M(table,{0})", idx);
try{
N(table,idx);}
catch {
Console.WriteLine("Reversing through M");
throw;
}
}
public static void N(int[] table, int idx){
Console.WriteLine("Calling N(table,{0})", idx);
try {
P(table,idx);}
catch {
Console.WriteLine("Reversing through N");
throw;
}
}
public static void P(int[] table, int idx){
Console.WriteLine("Calling P(table,{0})", idx);
try {
Console.WriteLine("Accessing element {0}: {1}",
idx, table[idx]);
}
catch {
Console.WriteLine("Error in P. Reversing through P");
throw;
}
}
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;
}
}
Main
Calling M(table,6)
Calling N(table,6)
Calling P(table,6)
Error in P. Reversing through P
Reversing through N
Reversing through M
Calling M(table,5)
Calling N(table,5)
Calling P(table,5)
Accessing element 5: 15