Nesting try Blocks


One try block can be nested within another. An exception generated within the inner try block that is not caught by a catch associated with that try is propagated to the outer try block. For example, here the IndexOutOfRangeException is not caught by the inner try block, but by the outer try:

 // Use a nested try block. using System; class NestTrys {   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 };     try { // outer try       for(int i=0; i < numer.Length; i++) {         try { // nested 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.");       Console.WriteLine("Fatal error -- program terminated.");     }   } }

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 No matching element found. Fatal error -- program terminated.

In this example, an exception that can be handled by the inner try—in this case a divide-by-zero error—allows the program to continue. However, an array boundary error is caught by the outer try, which causes the program to terminate.

Although certainly not the only reason for nested try statements, the preceding program makes an important point that can be generalized. Often, nested try blocks are used to allow different categories of errors to be handled in different ways. Some types of errors are catastrophic and cannot be fixed. Some are minor and can be handled immediately. Many programmers use an outer try block to catch the most severe errors, allowing inner try blocks to handle less serious ones. You can also use an outer try block as a catch-all block for those errors that are not handled by the inner block.




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