Catching All Exceptions


Sometimes you will want to catch all exceptions, no matter the type. To do this, use a catch statement that specifies no parameter. This creates a “catch all” handler that is useful when you want to ensure that all exceptions are handled by your program. For example, here the only catch is the “catch all,” and it catches both the IndexOutOfRangeException and the DivideByZeroException that is generated by the program:

 // Use the "catch all" catch statement. using System; class ExcDemo5 {   public static void Main() {     // Here, numer is longer than denom.     int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };     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 {         Console.WriteLine("Some exception occurred.");       }     }   } }

The output is shown here:

 4 / 2 is 2 Some exception occurred. 16 / 4 is 4 32 / 4 is 8 Some exception occurred. 128 / 8 is 16 Some exception occurred. Some exception occurred.

There is one point to remember about using a catch-all catch: It must be the last catch clause in the catch sequence.




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