What is Java finally block?
A Java finally block contains all the important statements that need to be executed whether an exception occurs or not. Regardless of exception a finally ensures that statements written inside finally-block should always execute. Like – closing a connection, file or stream.
Without catch-block
A finally-block can be used directly with the try-block. Finally-block will always execute even if an error occurs and it is not handled.
Syntax
try { // Body of try block. // Statements that may cause an exception } finally { // This block will always execute }
Example
Following is the example program, that shows how you can use finally-block without catch-block.
public class FinallyWithoutCatch { public static void main(String[] args) { try { // Do something here for (int i = 1; i <= 10; i++) { System.out.print(i + " "); } } finally { // This line will always execute System.out.println("END!"); } } }
With catch block
You can also write finally-block with catch-block, with catch block you can also handle the exception. See the below-shown syntax and example to better understand.
Syntax
try { // Body of try block. // Statements that may cause an exception } catch(<exception_class> <object_name>) { // Body of catch block. // Handling an exception } finally { // This block will always execute }
Example
Following is the example program, that shows how you can use finally-block with catch-block.
public class FinallyWithCatch { public static void main(String[] args) { int num = 0; try { // It will raise numer format exception num = Integer.parseInt("hello"); } catch (NumberFormatException e) { // Handle the exception System.out.println("Invalid number!"); } finally { // This line will always execute System.out.println("Number is: " + num); } } }