home page

finally block

The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
finally block

Note:Before terminating the program, JVM executes finally block(if any).

Note:finally must be followed by try or catch block.


Why use finally block?

  • finally block can be used to put "cleanup" code such as closing a file,closing connection etc.

case 1

Program in case exception does not occur
Test it Now
Output:5
       finally block is always executed
       rest of the code...

case 2

Program in case exception occured but not handled
Test it Now
Output:finally block is always executed
       Exception in thread main java.lang.ArithmeticException:/ by zero

case 3

Program in case exception occured and handled
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
       finally block is always executed
       rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Next TopicThrow Keyword