6.2 Using a finally Block You want to execute a body of code whether or not an exception is thrown. | Technique You can use a finally block to execute a block of code after executing the corresponding try / catch blocks. Immediately following a catch block or multiple catch blocks, use the keyword finally followed by a code block within curly braces. Listing 6.2 shows a try block followed by two catch blocks. The finally block in the code runs whether an exception is thrown or not. Listing 6.2 Adding a finally Block using System; namespace _1_TryCatch { class Class1 { [STAThread] static void Main(string[] args) { try { // retrieve number from user Console.Write( "Enter a number: "); int input = Int32.Parse( Console.ReadLine() ); // last iteration attempts to divide by zero for( int i = 5; i > 0; i-- ) Console.WriteLine( "{0}/{1}={2}", input, i, input/i ); } catch( DivideByZeroException ) { Console.WriteLine( "Program attempted to divide by zero" ); } catch( Exception e ) { Console.WriteLine( "An error occurred: {0}", e.Message ); } finally { Console.WriteLine( "Program has finished." ); } } } } Comments When an exception is thrown, the remainder of a try block does not execute, and control is transferred to a catch block. Any extra processing you have along the lines of cleaning up resources, ensuring out parameters are set correctly, or manipulating any internal variables is skipped . If you were to put that information within a catch block instead of a try block, then of course it wouldn't execute if an exception were never thrown. You could place duplicate code within the try and catch blocks, but this solution obviously isn't clean. The finally block executes common code that needs to be executed following either the end of a try block or the end of a catch block. It is a fair question to ask why you even need a finally block in the first place. After all, the lines of code following the try and catch blocks is executed anyway. That is true, and you are free to use that to your advantage. However, using a finally block keeps any variables declared within the try block in scope. Once the exception-handling blocks are exited, any variables that were declared within the try block are no longer valid and cannot be used. Therefore, you want to free any resources that were created within the try block, which can include any open streams or database connections, for example. |