If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

Answer from T.J. Crowder on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › flow-control-in-try-catch-finally-in-java
Flow control in try catch finally in Java - GeeksforGeeks
July 23, 2025 - 3. Exception doesn't occur in try-block: In this case catch block never runs as they are only meant to be run when an exception occurs. finally block(if present) will be executed followed by rest of the program.
Top answer
1 of 2
150

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

2 of 2
107

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
assert abstract boolean break byte ... short static super switch synchronized this throw throws transient try var void volatile while Java ......
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › finally.html
The finally Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
public void writeList() throws IOException { try (FileWriter f = new FileWriter("OutFile.txt"); PrintWriter out = new PrintWriter(f)) { for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } } } The try-with-resources statement automatically releases system resources when no longer needed. See The try-with-resources Statement. ... Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved. Previous page: The catch Blocks Next page: The try-with-resources Statement
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
The exception is propagated up the call stack like this until some method catches the exception, or the Java Virtual Machine does. You can attach a finally-clause to a try-catch block.
🌐
Programiz
programiz.com › java-programming › try-catch
Java try...catch (With Examples)
Here, the size of the array is 5 and the last element of the array is at list[4]. However, we are trying to access elements at a[5] and a[6]. Hence, the code generates an exception that is caught by the catch block. Since the finally block is always executed, we have included code to close the PrintWriter inside the finally block.
Find elsewhere
Top answer
1 of 9
182

It depends on whether you can deal with the exceptions that can be raised at this point or not.

If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.

If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

2 of 9
40

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.

The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.

Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.

🌐
Educative
educative.io › answers › how-to-use-the-try-catch-and-finally-blocks-in-java
How to use the try, catch, and finally blocks in Java
The catch block is used to handle the exception if it is thrown. The finally block is used to execute the code after the try and catch blocks have been executed.
🌐
Coderanch
coderanch.com › t › 412156 › java › catch-finally-return
try, catch, finally and return (Beginning Java forum at Coderanch)
You will have to go through the Java Language Specification for the different places where abrupt completion is described and compare them with the first link I gave. ... I found very interesting this thread and wanted to illustrate it with a code example for everybody. In this case, the catch clause contains a return statement. The output is as follows: Calling go Entered catch Entered finally Back from go: ok We can see that when execution hits return it does not immediately return, but rather gives the finally block a chance to execute before actually returning.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › try.html
The try Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
private List<Integer> list; private static final int SIZE = 10; public void writeList() { PrintWriter out = null; try { System.out.println("Entered try statement"); FileWriter f = new FileWriter("OutFile.txt"); out = new PrintWriter(f); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } } catch and finally blocks .
🌐
Medium
medium.com › thefreshwrites › try-catch-finally-in-java-exception-handling-2ed273814cd8
Try-Catch-Finally In Java | Exception Handling | by Mouad Oumous | The Fresh Writes | Medium
February 22, 2024 - A finally block appears at the end of catch block. finally blocks are used to nullify the object references and closing the I/O streams. The finally block always executes when the try block exits.
🌐
Scaler
scaler.com › topics › java › try-catch-and-finally-in-java
Try, Catch and Finally in Java | Scaler Topics
August 29, 2022 - When we have nested catch blocks, as soon as a catch matches the exception thrown, it executes the code inside it and then other catch blocks are ignored by the execution. The finally block (if present) is then executed and the execution continues. ...
🌐
CodingNomads
codingnomads.com › java-try-catch-finally
Java: Try Catch Finally
In Java, try-catch-finally is a longer version of the try-catch block, that ensures some code will always run regardless of the result of the try block. In this article, you'll learn how to use it.
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java try catch finally
Java try catch finally (with Examples) - HowToDoInJava
April 7, 2023 - If there is an exception occurred in try block, then JVM will execute catch block first and then finally block.
🌐
Quora
quora.com › How-is-try-catch-different-from-try-finally-in-Java
How is try-catch different from try-finally in Java? - Quora
Answer (1 of 7): The major difference is that the catch block is only executed if an exception occurs, while the finally block is alway executed after the try block. The major value in try-finally is that you can grab a resource in the try block, ...
🌐
ExamClouds
examclouds.com › home › java core
Handling Exceptions with Try-Catch and Finally Block in Java
A finally block should immediately follow the last catch block (or it must immediately follow the try block if there is no catch). Let's look at the simple example where an unchecked exception is caught.