try-catch-finally with return after it

19,561

Solution 1

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

Solution 2

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.

Solution 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

Solution 4

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.

Share:
19,561

Related videos on Youtube

Kevin Cruijssen
Author by

Kevin Cruijssen

Software developer from The Netherlands; 29 years old. Favorite programming languages: Java, 05AB1E, Whitespace I also collect puzzles: My Collection Visited StackOverflow frequently in the past to help others (and sometimes to ask help myself if needed), but currently I mainly focus on Code-Golf challenges. I once discovered a bug in Java 9 and Java 10 compilers while code-golfing. :)

Updated on September 16, 2022

Comments

  • Kevin Cruijssen
    Kevin Cruijssen over 1 year

    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.

    • Rohit Jain
      Rohit Jain about 10 years
      Why can't you just execute the code and see what value it returns?
    • Joffrey
      Joffrey about 10 years
      Because he's in a bus, and was just wondering ^^
  • Fildor
    Fildor about 10 years
    "That case" means "no exception" and "the other return" is the one after the finally block, right? (Just to make that clear)
  • Christophe Roussy
    Christophe Roussy about 10 years
    @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
  • Fildor
    Fildor about 10 years
    I am aware of that. I just found the phrasing you are using somewhat ambiguous ...
  • Christophe Roussy
    Christophe Roussy about 10 years
    @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.
  • Fildor
    Fildor about 10 years
    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
    Fildor about 10 years
    @JqueryLearner What makes you think it is unreachable?
  • Fildor
    Fildor about 10 years
    @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.
  • Mark Rotteveel
    Mark Rotteveel about 10 years
    @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.
  • Fildor
    Fildor about 10 years
    @MarkRotteveel agreed :)
  • Fildor
    Fildor about 10 years
    @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.
  • Christophe Roussy
    Christophe Roussy about 10 years
    @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.
  • Fildor
    Fildor about 10 years
    @JqueryLearner because you put a return in finally block. That makes everything after unreachable.
  • SpringLearner
    SpringLearner about 10 years
    @Fildor Its my fault,I thought OP has return statement in finally block also.So all this discussions is not useful.Sorry
  • Joffrey
    Joffrey about 10 years
    @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.