Categories
error-handling java return try-catch-finally

Does a finally block always get executed in Java?

2616

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}

9

  • 672

    If it didn’t, the keyword should be named probably instead.

    – Noon Silk

    May 13, 2010 at 6:18

  • 56

    Not always

    – Boann

    Sep 23, 2013 at 0:52

  • 3

    Effective java says otherwise informit.com/articles/article.aspx?p=1216151&seqNum=7

    Dec 14, 2014 at 3:08

  • 34

    @BinoyBabu, finalizer != finally; finalizer == the finalize() method.

    – jaco0646

    Jul 12, 2016 at 16:11

  • 4

    @Boann Correct, “not always” indeed. But then you can never ever use the words “guaranteed” or “always”.

    Jan 19, 2017 at 19:40

2936

Yes, finally will be called after the execution of the try or catch code blocks.

The only times finally won’t be called are:

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

16

  • 47

    Actually thread.stop() does not necessarily prevent finally block from being executed.

    Mar 30, 2011 at 21:12

  • 206

    How about we say that the finally block will be called after the try block, and before control passes to the following statements. That’s consistent with the try block involving an infinite loop and hence the finally block never actually being invoked.

    Sep 16, 2011 at 11:24

  • 9

    there is also another case, when we use nested try-catch-finally blocks

    – ruhungry

    Mar 22, 2014 at 20:39


  • 7

    also, finally block is not called in case of exception thrown by daemon thread.

    Sep 11, 2014 at 12:07

  • 15

    @BinoyBabu – That’s about finalizer, not finally block

    – avmohan

    Jan 5, 2017 at 10:17

614

Example code:

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

public static int test() {
    try {
        return 0;
    }
    finally {
        System.out.println("something is printed");
    }
}

Output:

something is printed. 
0

9

  • 20

    FYI: In C# the behaviour is identical apart from the fact that replacing the statement in the finally-clause with return 2; is not allowed (Compiler-Error).

    Oct 31, 2013 at 8:08

  • 15

    Here is an important detail to be aware of: stackoverflow.com/a/20363941/2684342

    Dec 3, 2013 at 23:37

  • 22

    You can even add a return statement in the finally block itself, which will then override the previous return value. This also magically discards unhandled exceptions. At that point, you should consider refactoring your code.

    – Zyl

    Apr 15, 2015 at 17:25


  • 10

    That does not really prove that finally trumps return. The return value is printed from the caller code. Doesn’t seem to prove much.

    – Trimtab

    Jun 21, 2016 at 4:20

  • 23

    Sorry, but this is a demonstration not a proof. It is only a proof if you can show that this example always behaves this way on all Java platforms, AND that similar examples also always behave this way.

    – Stephen C

    Aug 20, 2017 at 1:24

415

Also, although it’s bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:

try { return true; } finally { return false; }

Same thing with throwing exceptions from the finally block.

10

  • 102

    This is a REALLY bad practice. See stackoverflow.com/questions/48088/… for more info about why it’s bad.

    Sep 16, 2008 at 2:47

  • 23

    Agreed. A return within finally{} ignores any exception thrown in try{}. Scary!

    – neu242

    Oct 22, 2008 at 7:12

  • 10

    @dominicbri7 Why do you think it’s a better practice? And why should it be different when the function/method is void?

    – corsiKa

    Jul 12, 2011 at 20:26

  • 8

    For the same reason I NEVER use goto’s in my C++ codes. I think multiple returns makes it harder to read and more difficult to debug (of course in really simple cases it doesn’t apply). I guess that’s just personnal preferrence and in the end you can achieve the same thing using either method

    Jul 13, 2011 at 11:47

  • 18

    I tend to use a number of returns when some kind of exceptional case happens. Like if(there is a reason not to continue) return;

    Feb 22, 2013 at 23:24