I was wondering what's the difference between code inside finally block and code after finally block
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).
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With