- finally block will be executed always even exception occurs.
- If we explicitly call System.exit() method then only finally block will not be executed if exit() call is before finally block.
- There are few more rare scenarios where finally block will not be executed.
- When JVM crashes
- When there is an infinite loop
- When we kill the process ex:kill -9 (on unix)
- Power failure, hardware error or system crash.
- And as we discussed System.exit().
- Other than these conditions finally block will be executed always.
- finally block is meant to keep cleaning of resources. Placing code other than cleaning is a bad practice
- What happens if we place finally block after return statement? or
- Does finally block will execute after return statement??
- As per the above rules Yes finally will always execute except any interruption like System.exit() or all above mentioned conditions
Program #1 : Java example program which explains how finally block will be executed even after a return statement in a method.
- package com.instanceofjava.finallyblockreturn;
- /**
- * By: www.instanceofjava.com
- * program: does finally gets executed after return statement??
- *
- */
- public class FinallyBlockAfterReturn {
- public static int Calc(){
- try {
- return 0;
- } catch (Exception e) {
- return 1;
- }
- finally{
- System.out.println("finally block will be executed even when we
- place after return statement");
- }
- }
- public static void main(String[] args) {
- System.out.println(Calc());
- }
- }
Output:
- finally block will be executed even when we place after return statement
- 0
Can we place return statement in finally??
- Yes we can place return statement in finally and finally block return statement will be executed.
- But it is a very bad practice to place return statement in finally block.
No comments