Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between code inside finally block and code after finally block?

I was wondering what's the difference between code inside finally block and code after finally block

like image 530
pete Avatar asked May 28 '14 19:05

pete


3 Answers

A small test program shows the difference:

public class FinallyTest {

    public static void main(String[] args) throws Exception {
        try {
            boolean flag = true;
            if (flag) {
                throw new Exception("hello");
            }
        } finally {
            System.out.println("this will get printed");
        }
        System.out.println("this won't show up");
    }
}

The program throws an exception, the JVM executing the program catches it and prints it out.

What gets written to the console is:

this will get printed
Exception in thread "main" java.lang.Exception: hello
    at snippet.FinallyTest.main(FinallyTest.java:7)

Once the exception is thrown the only things that that thread will execute (until the exception is caught by the JVM) are finally blocks (where the exception is leaving a try-block that the finally belongs to).

like image 167
Nathan Hughes Avatar answered Sep 28 '22 09:09

Nathan Hughes


If the catch block re-throws an exception (or throws a new one), the finally block is executed. Anything after the finally block will not be executed.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. - http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

like image 38
S. Ahn Avatar answered Sep 28 '22 08:09

S. Ahn


If you throw the exception on the catch block, or if you return something on your try block, it will execute the finally block. If not on the finally block (after try/catch/finally) it wont work. Here is a simple example for you to understand: Try it without the finally block and you will see that the line where it prints the message "Closing resources..." will never be executed.

try {
    return "Something";
} catch (Exception e) {
    throw e;
} finally {
    System.out.println("Closing resources (Connections, etc.)...");//This will always execute
}
like image 25
Mateus Viccari Avatar answered Sep 28 '22 08:09

Mateus Viccari