7

Here is the example from You Don't Know JS:

for (var i=0; i<10; i++) {
    try {
        continue;
    }
    finally {
        console.log( i );
    }
}
// 0 1 2 3 4 5 6 7 8 9

How is it able to print all numbers if continue makes the loop jump over that iteration? To add to that, "console.log(i) runs at the end of the loop iteration but before i++" which should explain why it prints from 0 to 9?

p1xel
  • 97
  • 1
  • 9
  • 5
    `fnally` ALWAYS runs after its corresponding `try..catch` segment ends. `continue` ends the `try` at which point `finally` goes "hang on a minute, do this first!" and logs `i` before the `continue` is allowed to proceed. – Niet the Dark Absol Aug 15 '16 at 08:36
  • 3
    For another example, try `function test() {try {return 'foo';} finally {console.log('bar');}}` and you'll see that code after an unconditional `return` isn't necessarily dead. – Niet the Dark Absol Aug 15 '16 at 08:37
  • No matter what , finally block will be executed before going over to next iteration in for loop. Also, in for loop you told "set 'i' to zero, then increment it until it's incrementation is lower than 10, then stop". So , when it goes to number 10 it will result in break statement of loop. – Kadaj Aug 15 '16 at 08:38
  • @NiettheDarkAbsol why dont you put it in an answer so we can upvote it correctly :O – Bamieh Aug 15 '16 at 08:45
  • Possible duplicate of [Javascript error handling with try .. catch .. finally](http://stackoverflow.com/questions/286297/javascript-error-handling-with-try-catch-finally) – Bamieh Aug 15 '16 at 08:46

2 Answers2

6

In fact in a try ... catch statement, finally block will always be reached and executed.

So here in your case:

for (var i=0; i<10; i++) {
    try {
        continue;
    }
    finally {
        console.log( i );
    }
}

The finally block will be executed every iteration whatever you do in the try block, that's why all the numbers were printed.

Documentation:

You can see from the MDN try...catch Documentation that:

The finally clause contains statements to execute after the try block and catch clause(s) execute, but before the statements following the try statement. The finally clause executes regardless of whether or not an exception is thrown. If an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

Doc:

The finally clause contains statements to execute after the try block and catch clause(s) execute, but before the statements following the try statement. The finally clause executes regardless of whether or not an exception is thrown. If an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

So finally is always called after the catch statement.

Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49