Search code examples
javascriptjava-8nashorn

break and continue statements are causing finally block execution in Nashorn


I'm puzzled why finally is getting executed after break/continue (Version: Java 8 update 5)

testTryFinally();

function testTryFinally()
{
  try
  {
    print("Try 1");
    for(var i = 0; i < 2; i++)
    {
      break;
    }  
    print("Try 2");
  }
  finally
  {
    print("Finally executed");
  }
}

Execution: .../tmp>jjs test.js

Output with break:

Try 1
Finally executed
Try 2
Finally executed

Output with continue in place of break

Try 1
Finally executed
Finally executed
Try 2
Finally executed

I have tried executing the same code in browser (replacing print() with console.log()

Output is as expected in Firebug

Try 1
Try 2
Finally executed

Solution

  • I found the relevant statement here:

    . . . While it's true finally will always be executed if defined, certain statements inside try such as continue, break, return, or when an error has occurred and there is no catch clause will all cause finally to be executed immediately thereafter . . .

    But i don't see this is happening in Firefox (probably for a good reason)