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 in java

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



case 2

Program in case exception occured but not handled



case 3

Program in case exception occured and handled


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).