-1

I am trying to put a while loop inside a try /catch block. To my curiosity finally of that try catch is not executed when the while loop exits. Can some explain what is happening actually? I tried to google, but cnould not find any details.

Tinkerbel
  • 169
  • 1
  • 3
  • 13

2 Answers2

5

I assume your code looks like this:

try
{
    while (...)
    {
        // ...
    }
}
catch (FooException ex)
{
    // This only executes if a FooException is thrown.
}
finally
{
    // This executes whether or not there is an exception.
}

The catch block is only executed if there is an exception. The finally block usually executes whether or not an exception was thrown. So you will probably find that your finally block is actually being executed. You can prove this to yourself by placing a line there that causes some output to the console.

However there are situations in which the finally block doesn't run. See here for more details:

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

It can happen only if your program exits either by using System.exit() or if an Error or Throwable were thrown (vs. Exception that will be caught).

Try the following:

   public static void main(String[] args) {         
        try{
            System.out.println("START!");
            int i=0;
            while(true){
                i++;
                if(i > 10){
                    System.exit(1);
                }
            }
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        finally{
            System.out.println("this will not be printed!");
        }
    }
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129