14

I have this java code with nested try:

try
{   
    try
    {
        [ ... ]
    {
    catch (Exception ex)
    {
        showLogMessage(ex);
        return;
    }

    while (condition == true)
    {
        try
        {
            [ ... ]
        {
        catch (Exception ex)
        {
            showLogMessage(ex);
            continue;
        }

        [ ... ]
    }
}
catch (NumberFormatException e)
{
    showLogMessage(e);
}
finally
{
    doSomeThingVeryImportant();
}

I want to know if finally is always executed when I get an exception. I ask this because catch blocks have return or continue statements.

When is doSomeThingVeryImportant() executed? When I get an Exception on when I get a NumberFormatException?

I only want if after any catch block is executed, the finally block is executed also.

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • out of curiosity and extending of the question: is finally executed even after an `exit` statement? – Marco Forberg May 07 '13 at 06:48
  • You'd have run your code and seen for yourself, if it executes or not, when you get an exception! I really doubt if anything which is not present in the [docs](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) has been posted in any of the answers below! – Rahul May 07 '13 at 06:53
  • 1
    Please stop down voting. It isn't a duplicate question. – VansFannel May 07 '13 at 07:00

10 Answers10

20

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like this:

public void someMethod{
   Try {
   // some code
   }

   Catch(Exception x) {
   // some code
   }

   Catch(ExceptionClass y) {
   // some code
   }

   Finally{
   //this code will be executed whether or not an exception 
   //is thrown or caught
   }
}

There are 4 potential scenarios here:

  1. The try block runs to the end, and no exception is thrown. In this scenario, the finally block will be executed after the try block.

  2. An exception is thrown in the try block, which is then caught in one of the catch blocks. In this scenario, the finally block will execute right after the catch block executes.

  3. An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception. In this scenario, the call to the method ends, and the exception object is thrown to the enclosing method - as in the method in which the try-catch-finally blocks reside. But, before the method ends, the finally block is executed.

  4. Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block willstill be executed even if there is a return statement somewhere in the try block.

Update: Finally ALWAYS gets executed, no matter what happens in the try or catch block (fail, return, exception, finish etc.).

Jainendra
  • 24,713
  • 30
  • 122
  • 169
  • I only want if after any catch block is executed, the finally block is executed also. – VansFannel May 07 '13 at 07:01
  • 1
    @VansFannel Yes it will execute, no matter if catch is being called or not – Jainendra May 07 '13 at 07:03
  • Sorry, but I don't asking that. I ask if after a catch block with a return statement inside, the finally method is executed or if return without execution. And there are catch block with a continue inside. I want to know if after continue call, finally is executed. – VansFannel May 07 '13 at 07:06
  • 1
    Yes then also it will be called Because that's the whole point of a finally block. See my update – Jainendra May 07 '13 at 07:09
  • 2
    this should be the correct answer – aran Mar 11 '16 at 11:24
8

The finally block always executes when the try block exits (click).

tostao
  • 2,803
  • 4
  • 38
  • 61
  • 1
    I have changed the question. – VansFannel May 07 '13 at 06:55
  • It won't always. If a System.exit() calls, finally won't get executed. – Maximin May 07 '13 at 06:59
  • @tostao I cannot agree with you. What do you think about http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java/22583252#22583252 – ruhungry Mar 22 '14 at 21:01
  • 1
    This is correct - why is it voted down? Crashing, exiting on purpose, etc. do not count as exceptions in this case as the question obviously implies what happens when the code/program continues execution not when the computer crashes, there is a power failure or the user exits in purpose - sure then nothing executes. – Fotios Basagiannis Jan 20 '17 at 23:55
2
The finally block always executes when the try block exits. 
This ensures that the finally block is executed even if an unexpected exception occurs

Taken from here: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Further, the page explains that the finally block may not be executed if the JVM exists while the try or catch code is being executed, or if the thread executing the try/catch is interrupted or killed.

So unless you may kill the JVM or the try/catch is beeing executed in a thread, the finally block will always be executed

John Snow
  • 5,214
  • 4
  • 37
  • 44
  • I have changed the question. – VansFannel May 07 '13 at 06:56
  • The finally block will be run even if there is an exception and if you return/break/Continue in a catch block. The only time it may not be run is if the JVM dies or the thread executing the try/catch is killed or interrupted. So the answer to your question is YES – John Snow May 07 '13 at 06:58
2

Yes, Finally always executes. With exception and with NO exception.

It's the way to be sure some portion of code get always executed.

Used for example, to dispose objects, to close opened server connections and that kind of stuff.

Check this link from oracle:

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

Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
2

Yes, finally blocks are always executed.

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

2

Yes; or, at least, as close to "always" as possible. (So, even if you have a return or another throw.)

If your process is killed, or your program gets stuck in a deadlock or infinite loop, or your device is struck by a meteor, then program flow will not reach the finally block.

killscreen
  • 1,657
  • 12
  • 14
2

Say your code block is something like this :

 try
    {   
        try
        {
            System.out.println("first try block");
        }
        catch (Exception ex)
        {
            System.out.println("first cathc block");
            return;
        }

        while (true)
        {
            try
            {
               System.out.println("second try block...");
            }
            catch (Exception ex)
            {
                System.out.println("second catch block");
                continue;
            }

            System.out.println("end of loop");
            break;
        }
    }
    catch (NumberFormatException e)
    {
        System.out.println("last catch block");
    }
    finally
    {
        System.out.println("finally block");
    }

If you run this then the output that you will get is :

first try block
second try block...
end of loop
finally block

So finally block gets executed anyway.

Madhusudan Joshi
  • 4,438
  • 3
  • 26
  • 42
0

Yes finally always gets executed and its because one can program to close/handle resources in case of exceptions or no exception without fail.

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


Update to answer the question in comment about System.exit()

The finally block will not execute in case of System.exit() unless it fails with some SecurityException.


Update after question changed. No matter what the exception is finally block will always execute.

If its Exception then your catch block will not execute as it catches only NumberFormatException

bemeyer
  • 6,154
  • 4
  • 36
  • 86
Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
0

Yes, finally blocks are always executed. But terms and conditions apply .

Untill unless you call System.exit();

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

No, finally won't get execute always. There are two situations where Finally won't get execute.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

java reference

For your question, if these two things are not there, whatever inside your finally will get executed, that's sure.

Maximin
  • 1,655
  • 1
  • 14
  • 32
  • I have changed the question. – VansFannel May 07 '13 at 06:58
  • @VansFannel Whether you get a exception or not, finally will get executed always. If there is a finally associated with try, if a exception occurs or not, finally will surely be executed – Maximin May 07 '13 at 07:02