javacodex.com
Java Examples
Java Examples
memu home questions

Try Block Where Finally Clause Does Not Run

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.

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

Source: (FinallyNotRun.java)

// Example of finally clause that does not run
public class FinallyNotRun {
   public static void main(String[] args) {
      try {
        System.out.println("Inside try");
 
        // should throw exception
        int x = 10 / 0;
 
      } catch (Exception e) {
        System.out.println("Inside catch");
 
        // Lets pretent to crash
        System.exit(0);
 
      } finally {
        // Will not run
        System.out.println("Inside finally");
      }
   }
}
 

Output:

$ java FinallyNotRun 
Inside try
Inside catch

Contact: javacodex@yahoo.com