3.1.6 The finally Clause3.1.5 Catching Multiple Exception Types3.1 Exception Handling3.1.7 Exceptions Thrown by Handlers

3.1.6 The finally Clause

A try statement may be terminated by a finally clause:  

   try
   {
     ... // protected code block
   }
   catch (Exception1 e1)
   {
     ... // exception handler 1
   }
   ...
   finally
   {
     ... // executed before try statement is exited
   }

The code in the finally clause is executed before the try statement is exited, in any of the three possible situations:

  1. if the protected code block does not throw an exception,
  2. if an exception is thrown and caught by one of the handlers,
  3. if an exception is thrown and not caught by any of the handlers.

For instance, if a file has been opened in the protected code block, the code in the finally clause can make sure that the file is closed in any (also the error) case.

We will see an example of this later.
Please note that the same may be not achieved by placing such code after the try statement: if an exception is thrown and not caught by any handler of this statement, this code is not executed.
© Wolfgang Schreiner; February 3, 2005

3.1.6 The finally Clause3.1.5 Catching Multiple Exception Types3.1 Exception Handling3.1.7 Exceptions Thrown by Handlers