Monday, September 14, 2009

Does finally block always execute?

I had always thought that the finally block in a try-catch-finally statement always executes. But this is not true. I found one exceptional case where the finally block does not execute.

Please see the below code example.

public class TestException
{

    static int choice = 5;
   
    public static void main(String[] args)
   {
      try{
             if (choice != 5)
            {
                System.out.println("hello");
             }
             else
            {
               System.out.println("In else");
               System.exit(1);
             }
           }
      finally
      {
          System.out.println("in finally");
       }
   }
}