Nested try Blocks


Nested try Blocks

You can insert a try block inside another try block to form nested try blocks. An unlimited number of nested try blocks can be written inside each other. Any uncaught exceptions of an inner try block moves through each of its outer try blocks one by one from innermost to outermost in search of a matching catch block. If no match is found, the runtime's default exception handler will handle the exception as shown earlier.

Listing 19.5 provides a simple example of one try-catch block nested inside another try block.

Listing 19.5 NestingTryBlocks.cs
01: using System; 02: 03: class TryNestTester 04: { 05:     public static void Main() 06:     { 07:         try 08:         { 09:             try 10:             { 11:                 int[] myArray = new int[10]; 12: 13:                 myArray[50] = 498; 14:             } 15:             catch(DivideByZeroException exObj) 16:             { 17:                 Console.WriteLine("Inside inner catch block"); 18:                 Console.WriteLine("Exception: " + exObj.Message); 19:             } 20:         } 21:         catch(IndexOutOfRangeException exObj) 22:         { 23:             Console.WriteLine("Inside outer catch block"); 24:             Console.WriteLine("Exception: " + exObj.Message); 25:         } 26:     } 27: } Inside outer catch block Exception: An exception of type System.IndexOutOfRangeException was thrown. 

The code of the inner try block (lines 9 14) throws an IndexOutOfRangeException in line 13, but no match is found in the corresponding catch block (lines 15 19). Consequently, the exception object is passed to the outer try block where a matching catch block is found in lines 21 25.



Even though it is less obvious, Listing 19.4 also contains nested try blocks. When a function call (such as the calls to MethodA and MethodB in lines 11 and 12) is enclosed in a try block and the function that is called also contains a try block (as MethodA and MethodB), this latter try block is nested inside the try block from where its function is called.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: