Exceptions Let You Handle Errors Gracefully


One of the key benefits of exception handling is that it enables your program to respond to an error and then continue running. For example, consider the following example that divides the elements of one array by the elements of another. If a division-by-zero occurs, a DivideByZeroException is generated. In the program, this exception is handled by reporting the error and then continuing with execution. Thus, attempting to divide by zero does not cause an abrupt runtime error resulting in the termination of the program. Instead, it is handled gracefully, allowing program execution to continue.

 // Handle error gracefully and continue. using System; class ExcDemo3 {   public static void Main() {     int[] numer = { 4, 8, 16, 32, 64, 128 };     int[] denom = { 2, 0, 4, 4, 0, 8 };     for(int i=0; i < numer.Length; i++) {       try {         Console.WriteLine(numer[i] + " / " +                           denom[i] + " is " +                           numer[i]/denom[i]);       }       catch (DivideByZeroException) {         // catch the exception         Console.WriteLine("Can't divide by Zero!");       }     }   } }

The output from the program is shown here:

 4 / 2 is 2 Can't divide by Zero! 16 / 4 is 4 32 / 4 is 8 Can't divide by Zero! 128 / 8 is 16

This example makes another important point: Once an exception has been handled, it is removed from the system. Therefore, in the program, each pass through the loop enters the try block anew—any prior exceptions have been handled. This enables your program to handle repeated errors.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net