Finally Block
Finally Block
Introduction
• Java finally block is a block used to execute important code such as
closing the connection, etc.
• Java finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.
• The finally block follows the try-catch block.
Flowchart
finally block in Java can be used to put important code which
needs to get executed such as closing a file, closing connection,
etc.
Usage of finally
• Case 1: When an exception does not occur
1.class TestFinally {
2. public static void main(String args[]){
3. try{
4.//below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8.//catch won't be executed
9. catch(NullPointerException e){
10.System.out.println(e);
11.}
12.//executed regardless of exception occurred or not
13. finally {
14.System.out.println("finally block is always executed");
15.}
16.
17.System.out.println("rest of the code...");
18. }
19.}
• Case 2: When an exception occurr but not handled by the catch block
1.public class TestFinally {
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside the try block");
5. //below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. //cannot handle Arithmetic type exception
10. //can only accept Null Pointer type exception
11. catch(NullPointerException e){
12. System.out.println(e);
13. }
14. //executes regardless of exception occured or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }
• Case 3: When an exception occurs and is handled by the catch block
1.public class TestFinally{
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. //below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. //handles the Arithmetic Exception / Divide by zero exception
10. catch(ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. //executes regardless of exception occured or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }
inprotected.com