Using Multiple catch Statements


You can associate more than one catch statement with a try. In fact, it is common to do so. However, each catch must catch a different type of exception. For example, the program shown here catches both array boundary and divide-by-zero errors:

 // Use multiple catch statements. using System; class ExcDemo4 {   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 (DivideByZeroException) {         // catch the exception         Console.WriteLine("Can't divide by Zero!");       }       catch (IndexOutOfRangeException) {         // catch the exception         Console.WriteLine("No matching element found.");       }     }   } }

This program produces the following output:

 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 No matching element found. No matching element found.

As the output confirms, each catch statement responds only to its own type of exception.

In general, catch expressions are checked in the order in which they occur in a program. Only a matching statement is executed. All other catch blocks are ignored.




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