Using finally


Sometimes you will want to define a block of code that will execute when a try/catch block is left. For example, an exception might cause an error that terminates the current method, causing its premature return. However, that method may have opened a file or a network connection that needs to be closed. Such types of circumstances are common in programming, and C# provides a convenient way to handle them: finally.

To specify a block of code to execute when a try/catch block is exited, include a finally block at the end of a try/catch sequence. The general form of a try/catch that includes finally is shown here:

 try {    // block of code to monitor for errors } catch (ExcepType1 exOb) {    // handler for ExcepType1 } catch (ExcepType2 exOb) {    // handler for ExcepType2 } . . . finally {    // finally code }

The finally block will be executed whenever execution leaves a try/catch block, no matter what conditions cause it. That is, whether the try block ends normally or because of an exception, the last code executed is that defined by finally. The finally block is also executed if any code within the try block or any of its catch statements returns from the method.

Here is an example of finally:

 // Use finally. using System; class UseFinally {   public static void genException(int what) {     int t;     int[] nums = new int[2];     Console.WriteLine("Receiving " + what);     try {       switch(what) {         case 0:           t = 10 / what; // generate div-by-zero error           break;         case 1:           nums[4] = 4; // generate array index error.           break;         case 2:           return; // return from try block       }     }     catch (DivideByZeroException) {       // catch the exception       Console.WriteLine("Can't divide by Zero!");       return; // return from catch     }     catch (IndexOutOfRangeException) {       // catch the exception       Console.WriteLine("No matching element found.");     }     finally {       Console.WriteLine("Leaving try.");     }   } } class FinallyDemo {   public static void Main() {     for(int i=0; i < 3; i++) {       UseFinally.genException(i);       Console.WriteLine();     }   } }

Here is the output produced by the program:

 Receiving 0 Can't divide by Zero! Leaving try. Receiving 1 No matching element found. Leaving try. Receiving 2 Leaving try.

As the output shows, no matter how the try block is exited, the finally block is executed.

One other point: syntactically, when a finally block follows a try block, no catch statements are technically required. However, any exceptions that occur will not be caught.




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