Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Saturday, December 18, 2021

Java Finally Block: Does Finally Execute After Return?

1. Introduction


In this tutorial, You'll be learning core java concepts as part of exception handling "Java finally block when return statement is encountered"

This is a famous interview question "will finally block is executed after return statement".
Answer is Yes, The finally block is executed even after a return statement in the method. So, finally block will always be executed even whether an exception is raised or not in java.

Finally Block: Will a finally block execute after a return statement in a method in Java?


We will look into the following in this article.
  • Finally block is executed right after try or catch blocks.
  • Scenarios where finally() block not executed
  • Does finally block Override the values returned by the try-catch block?
  • When happens to finally block execution if System.exit(1) is invoked?

2. Example to see finally block is executed after return statement in a method

This is a simple example program to demonstrate the scenario.

Example to see finally block is executed after return statement in a method


package com.javaprogramto.exception;

public class FinallyBlockAfterReturn {

    public static void main(String[] args) {

        int returnedStatus = process();
        System.out.println("Returned value : "+returnedStatus);

    }

    public static int process() {

        try {

            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.println("Executing Finally block after return statement.");
        }
    }
}

Example to see finally block is executed after return statement in a method


Output:

Executing Finally block after return statement.
Returned value : 1

3. Scenarios where finally() block not executed


Now, let us look at the scenarios where the final block is not executed.

There are possible cases where absolutely finally block will not be executed at all.

  • If you invoke System.exit()
  • If you invoke Runtime.getRuntime().halt(exitStatus)
  • If the JVM crashes first
  • If the JVM reaches an infinite loop (or some other non-interruptible, non-terminating statement) in the try or catch block
  • If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX
  • If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  • If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

4. Does finally block Override the values returned by the try-catch block?


If we have a return statement in try and finally blocks then finally block will override the value of try block.

Below is the example program and observe the output.

From try block, we are returning value "Success" and finally block "Good To Go".

And also, our program is not throwing any exception.

package com.javaprogramto.exception;

public class FinallyBlockReturnsValue {

    public static void main(String[] args) {

        String returnedStatus = executeReqeust();
        System.out.println("Status of the request: " + returnedStatus);

    }

    public static String executeReqeust() {

        try {

            System.out.println("Executing business logic");
            // doing business logic            return "Success";
        } catch (Exception e) {
            return "Error";
        } finally {

            System.out.println("Executing Finally block after return statement.");
            return "Good To Go";
        }
    }
}

Output:


Executing business logic
Executing Finally block after return statement.
Status of the request: Good To Go
Finally block overrides the value returned from try block. From the above code, It has returned and printed "Good To Go" from finally block instead of "Success" from try block.

5. When happens to finally block execution if System.exit(1) is invoked?


package com.javaprogramto.exception;

public class FinallyBlockSystemExit {

    public static void main(String[] args) {

        executeReqeust();
        System.out.println("Execution of main method is done");

    }

    public static void executeReqeust() {

        try {

            System.out.println("Executing business logic Started");
            // doing business logic            System.exit(1);
            System.out.println("Executing business logic Ended");
        } catch (Exception e) {

        } finally {

            System.out.println("Executing Finally block after return statement.");
            
        }
    }
}

Output:
Executing business logic Started

Based on the above output, After the invocation of the System.exit() no statement has been executed. So finally block also will not be executed in case of System.exit(1) or Runtime.getRuntime().halt(exitStatus) methods are executed.

6. Conclusion


In this article, You have seen a famous interview question to check the core java skills for 2-5 years of an experienced developer.

Seen the examples programs on Finally Block: Will a finally block execute after a return statement in a method in Java?

How to skip the execution of finally block with System.exit() or Runtime.halt() method.

As usual, all examples shown are on GitHub.


No comments:

Post a Comment

Please do not add any spam links in the comments section.