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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With