Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a finally block always get executed in Java?

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"); } 
like image 893
jonny five Avatar asked Sep 15 '08 17:09

jonny five


People also ask

Is finally block always executed Java?

A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.

When finally block will not be executed in Java?

A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.

Is finally block always executed after return?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

Can we skip execution of finally block?

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System.


1 Answers

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
like image 122
jodonnell Avatar answered Sep 17 '22 23:09

jodonnell