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.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_try_catch.asp
Java Exceptions (Try...Catch)
assert abstract boolean break byte ... static super switch synchronized this throw throws transient try var void volatile while Java ......
Discussions

What is the purpose of `finally` in `try/catch/finally`?
The finally part executes even if the exception was not caught (because it wasn't the type matched by the catch or because there was no catch clause at all), if the catch clause re-throws the exception or throws another exception, or if either of the clauses returns or otherwise jumps out of the current block. More on reddit.com
๐ŸŒ r/AskProgramming
18
11
September 18, 2019
java - Difference between try-finally and try-catch - Stack Overflow
Finally will be always executed after try and catch blocks whether there is an exception raised or not. ... Generally when we use any resources like streams, connections etc.. we have to close them explicitly using finally block. In the program given below we are reading data from a file using FileReader and we are closing it using finally block. import java... More on stackoverflow.com
๐ŸŒ stackoverflow.com
language agnostic - Why use try โ€ฆ finally without a catch clause? - Software Engineering Stack Exchange
An example where try... finally without a catch clause is appropriate (and even more, idiomatic) in Java is usage of Lock in concurrent utilities locks package. More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
January 23, 2012
coding style - Throwing an exception inside finally - Software Engineering Stack Exchange
Worth noting is that some of the Stream implementations in Java can't actually throw Exceptions on close(), but the interface declares it because some of them do. So, in some circumstances you might be adding a catch block which will never actually be needed. ... What's so nasty about using a try/catch block within a finally ... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
March 1, 2013
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
๐ŸŒ
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
Find elsewhere
๐ŸŒ
Jenkov
jenkov.com โ€บ tutorials โ€บ java-exception-handling โ€บ basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
October 25, 2022 - 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.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 412156 โ€บ java โ€บ catch-finally-return
try, catch, finally and return (Beginning Java forum at Coderanch)
October 3, 2008 - 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.
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.

๐ŸŒ
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.
๐ŸŒ
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, ...
๐ŸŒ
Scaler
scaler.com โ€บ topics โ€บ java โ€บ try-catch-and-finally-in-java
Try, Catch and Finally in Java | Scaler Topics
May 5, 2024 - 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. ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ exceptions-in-java
Java Exception Handling - GeeksforGeeks
If an exception occurs, remaining try code is skipped and JVM searches for a matching catch block. If found, the catch block executes. Control then moves to the finally block (if present).
Published ย  3 weeks ago
๐ŸŒ
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.
๐ŸŒ
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 .
๐ŸŒ
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.
๐ŸŒ
Quora
quora.com โ€บ What-is-the-possible-combination-of-try-catch-and-finally-block-in-Java
What is the possible combination of try, catch, and finally block in Java? - Quora
Answer (1 of 2): In Java, you can combine try, catch, and finally blocks in different ways depending on your requirements. Here are a few possible combinations: 1. Basic try-catch-finally: 2. Nested try-catch-finally: 3. Multiple catch blocks with a common exception handler: there are many possi...
Top answer
1 of 5
23

Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away. Worse, if your main block of code throws an exception, the exception raised in the finally block will hide it. It will look like the error was caused by the call to close, not for the real reason.

Some people follow a nasty pattern of nested exception handlers, swallowing any exceptions thrown in the finally block.

SomeFileWriter writer = null; 
try { 
     //init the writer
     //write into the file
} finally {
    if (writer!= null) {
        try {
            writer.close();
        } catch (...) {
            // swallow
        }
    }
}

In older versions of Java, you can "simplify" this code by wrapping resources in classes that do this "safe" clean up for you. A good friend of mine creates a list of anonymous types, each that provide the logic for cleaning up their resources. Then his code simply loops over the list and calls the dispose method within the finally block.

2 of 5
11

What Travis Parks said is true that exceptions in the finally block will consume any return values or exceptions from the try...catch blocks.

If you're using Java 7, though, the problem can be solved by using a try-with-resources block. According to the docs, as long as your resource implements java.lang.AutoCloseable (most library writers/readers do now), the try-with-resources block will close it for you. The additional benefit here is that any exception that occurs while closing it will be suppressed, allowing the original return value or exception to pass up.

From

FileWriter writer = null;
try {
  writer = new FileWriter("myFile.txt");
  writer.write("hello");
} catch(...) {
  // return/throw new exception
} finally {
  writer.close(); // an exception would consume the catch block's return/exception
}

To

try (FileWriter writer = new FileWriter("myFile.txt")) {
  writer.write("hello");
} catch(...) {
  // return/throw new exception, always gets returned even if writer fails to close
}

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ csharp โ€บ language-reference โ€บ statements โ€บ exception-handling-statements
Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn
You use a try-catch-finally statement both to handle exceptions that might occur during execution of the try block and specify the code that must be executed when control leaves the try statement: