Java Programming/Keywords/finally

From Wikibooks, open books for an open world
Jump to: navigation, search

finally is a keyword.

It is an optional part of a try block. The code inside the finally block will always be executed. This is also true for cases when there is an exception or even executed return statement in the try block.

Three things can happen in a try block:

  • No exception is thrown. In such a case, the following are executed:
    • code in the try block
    • code in the finally block
    • code after the try-catch block
  • An exception is thrown and a matching catch block found. In such a case, the following are executed:
    • code in the try block until where the exception occurred
    • code in the matched catch block
    • code in the finally block
    • code after the try-catch block
  • An exception is thrown and no matching catch block exists. In such a case, the following are executed:
    • code in the try block until where the exception occurred
    • code in the finally block

Note: in that third and final case, NO CODE after the try-catch block is executed.

For example:

Computer code
public void method() throws NoMatchedException
{
   try {
   //...
     throw new MyException_1();
   //...
   } catch ( MyException_1 e ) {
     // --- Handle the Exception_1 here --
   } catch ( MyException_2 e ) {
     // --- Handle the Exception_2 here --
   } finally {
     // --- This will always be executed no matter what --
   }
   // --- Code after the try-catch block
}

Note: if there is an exception that happens before the try-catch block, the finally block is not executed.

If return statement is used inside finally, it overrides the return statement in the try-catch block. For instance, the construct

Computer code
try {
   return 11;
 }  finally {
   return 12;
 }


will return 12, not 11. Professional code almost never contains statements that alter execution order (like return, break, continue) inside the finally block, as such code is more difficult to read and maintain.

See also: