Catching one of C#’s standard exceptions, as the preceding program does, has a side benefit: It prevents abnormal program termination. When an exception is thrown, it must be caught by some piece of code somewhere. In general, if your program does not catch an exception, it will be caught by the C# runtime system. The trouble is that the runtime system will report an error and terminate the program. For instance, in this example, the index out-of-bounds exception is not caught by the program:
// Let the C# runtime system handle the error. using System; class NotHandled { public static void Main() { int[] nums = new int[4]; Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. for(int i=0; i < 10; i++) { nums[i] = i; Console.WriteLine("nums[{0}]: {1}", i, nums[i]); } } }
When the array index error occurs, execution is halted and the following error message is displayed:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at NotHandled.Main()
While such a message is useful for you while debugging, it would not be something that you would want others to see, to say the least! This is why it is important for your program to handle exceptions itself.
As mentioned earlier, the type of the exception must match the type specified in a catch statement. If it doesn’t, the exception won’t be caught. For example, the following program tries to catch an array boundary error with a catch statement for a DivideByZeroException (another of C#’s built-in exceptions). When the array boundary is overrun, an IndexOutOfRangeException is generated, but it won’t be caught by the catch statement. This results in abnormal program termination.
// This won't work! using System; class ExcTypeMismatch { public static void Main() { int[] nums = new int[4]; try { Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. for(int i=0; i < 10; i++) { nums[i] = i; Console.WriteLine("nums[{0}]: {1}", i, nums[i]); } Console.WriteLine("this won't be displayed"); } /* Can't catch an array boundary error with a DivideByZeroException. */ catch (DivideByZeroException) { // catch the exception Console.WriteLine("Index out-of-bounds!"); } Console.WriteLine("After catch statement."); } }
The output is shown here:
Before exception is generated. nums[0]: 0 nums[1]: 1 nums[2]: 2 nums[3]: 3 Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at ExcTypeMismatch.Main()
As the output demonstrates, a catch for DivideByZeroException won’t catch an IndexOut OfRangeException.