Java Finally block
In the previous chapter we have studied the nested try and catch blocks in this chapter we will be learning the finally block.
Contents
Finally block : Exception Handling in Java
- Finally Block in always executed irrespective of exception is handled or not
- Finally is not a function, It is keyword in java
- Finally performs the functions such as closing the stream or file and closing connections.
- Finally always gets executed before terminating the program by JVM.
- Finally should be after try and catch and is optional
- Each try block has minimum 0 and maximum 1 finally block.
Flowchart for Finally Statement -
Finally block : Syntax
try { ------- ------- } catch(Exception e) { ------- ------- } finally { }
Tip 1 : Finally block is optional
In the program we can have minimum zero and maximum one finally statement.
public class MyExceptionExample { public static void main(String[] a){ try{ int i = 10/0; } catch(Exception ex){ System.out.println("Inside 1st catch Block"); } try{ int i = 10/10; } catch(Exception ex){ System.out.println("Inside 2nd catch Block"); } finally { System.out.println("Inside 2nd finally block"); } } }
In the 1st try statement block we can see that we don’t have finally block but in the 2nd try block we have finally block. So finally block is always optional.
finally { System.out.println("Inside 2nd finally block"); }
2nd try block does not throw any exception but still after the execution of try block code executes finally statement block
Output :
Inside 1st catch Block Inside 2nd finally block
Tip 2 : Finally block is not executed in below two cases
- If following statement is included in the try block (Terminating code using system exit)
- If the thread executing the try or catch code is interrupted or killed, the finally statement block may not execute [For more info]
System.exit(0);