27

I know how try, catch & finally work (for most part), but I have one thing I was wondering: what happens with a return statement after a try-catch-finally, while we already had a return in the try (or catch)?

For example:

public boolean someMethod(){
    boolean finished = false;
    try{
        // do something
        return true;
    }
    catch(someException e){
        // do something
    }
    finally{
        // do something
    }
    return finished;
}

Let's say nothing went wrong in the try, so we returned true. Then we will go to the finally where we do something like closing a connection, and then?

Will the method stop after we did some stuff in the finally (so the method returned true in the try), or will the method continue after the finally again, resulting in returning finished (which is false)?

Thanks in advance for the responses.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135

5 Answers5

27

The fact that the finally block is executed does not make the program forget you returned. If everything goes well, the code after the finally block won't be executed.

Here is an example that makes it clear:

public class Main {

    public static void main(String[] args) {
        System.out.println("Normal: " + testNormal());
        System.out.println("Exception: " + testException());
    }

    public static int testNormal() {
        try {
            // no exception
            return 0;
        } catch (Exception e) {
            System.out.println("[normal] Exception caught");
        } finally {
            System.out.println("[normal] Finally");
        }
        System.out.println("[normal] Rest of code");
        return -1;
    }

    public static int testException() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.out.println("[except] Exception caught");
        } finally {
            System.out.println("[except] Finally");
        }
        System.out.println("[except] Rest of code");
        return -1;
    }

}

Output:

[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1
Joffrey
  • 32,348
  • 6
  • 68
  • 100
10

If all goes well, return inside the try is executed after executing the finally block.

If something goes wrong inside try, exception is caught and executed and then finally block is executed and then the return after that is executed.

Dhanush Gopinath
  • 5,652
  • 6
  • 37
  • 68
  • @JqueryLearner What makes you think it is unreachable? – Fildor Mar 20 '14 at 12:46
  • 3
    @JqueryLearner The finally block is not the end. Try it out. All code after it will be perfectly reachable. And finally returns nothing at all. It is just a block of code that is executed unaware of if there was an exception or not. – Fildor Mar 20 '14 at 12:50
  • @JqueryLearner For a different reason, though. Drop the return inside the finally and place something inside tryblock that actually _could_ throw an exception. It will compile and run. – Fildor Mar 20 '14 at 12:54
  • 1
    @JqueryLearner because you put a return in finally block. That makes everything after unreachable. – Fildor Mar 20 '14 at 12:56
  • @Fildor Its my fault,I thought OP has return statement in finally block also.So all this discussions is not useful.Sorry – SpringLearner Mar 20 '14 at 12:59
3

In that case the code inside the finally is run but the other return is skipped when there are no exceptions. You may also see this for yourself by logging something :)

Also see this concerning System.exit: How does Java's System.exit() work with try/catch/finally blocks?

And see returning from a finally: Returning from a finally block in Java

Community
  • 1
  • 1
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
  • "That case" means "no exception" and "the other return" is the one after the finally block, right? (Just to make that clear) – Fildor Mar 20 '14 at 12:38
  • @Fildor if there is an exception the 2nd return will be used but the finally block is still executed. As I said you can try do this yourself in a small program in a main and see what happens by system.out or logging or a break point – Christophe Roussy Mar 20 '14 at 12:39
  • I am aware of that. I just found the phrasing you are using somewhat ambiguous ... – Fildor Mar 20 '14 at 12:40
  • @Fildor yes I only covered the case without the exception as I thought it was the most interesting. This is the default pre Java 7 way (using finally) to close resources. – Christophe Roussy Mar 20 '14 at 12:42
  • If I remember correctly, it is recommended to not return inside try, though but rather you would set `finished` and have it return in one place, only. – Fildor Mar 20 '14 at 12:44
  • @Fildor The position of a `return` is subject to holy wars; it is mostly a matter of taste, convention and coding standard at your place of work. – Mark Rotteveel Mar 20 '14 at 12:51
  • @MarkRotteveel agreed :) – Fildor Mar 20 '14 at 12:52
  • @Fildor this works if the variable has been initialized before the try, if it was not then you have to use the double return idiom. – Christophe Roussy Mar 20 '14 at 12:55
2
public int Demo1()
    {
        try{
            System.out.println("TRY");
            throw new Exception();
            }catch(Exception e){
                System.out.println("CATCH");
            }finally{
                System.out.println("FINALLY");
            }return 0;

    }

the output of call to this method is like this

TRY
CATCH
FINALLY
0

Means Consider Try{}catch{}finally{} as sequence of statements executed one by one In this particular case. And than control goes to return.

akash
  • 22,664
  • 11
  • 59
  • 87
0

Definitely the code inside try will execute.. but when it reaches to return statement.. it will move to the finally block without executing the return statement in try block.. and then the code of finally will be executed and then the return statement of try will execute.

  • @Narendra11744 Just no. Try some code if you don't know the result, but don't put a wrong answer please. If no exception occurred, after the finally block, the return statement in the try will be executed, nothing else. – Joffrey Mar 20 '14 at 13:09