Home » Android » java – When finally is executed?

java – When finally is executed?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

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.).

Answer:

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

Answer:

Yes, finally blocks are always executed.

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

Answer:

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.

Answer:

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.

Answer:

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

Answer:

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

Untill unless you call System.exit();

Answer:

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

Answer:

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.