finally
blocks JS-0026617 }
618 finally
619 {
620 return;621 }
622}
623
76 }
77 finally
78 {
79 return;80 }
81}
82
32 }
33 finally
34 {
35 return;36 }
37}
38
381 }
382 finally
383 {
384 return;385 }
386}
387
96 }
97 finally
98 {
99 return;100 }
101}
102
The usage of control flow statements like return
, throw
, break
, and continue
inside finally
blocks is not recommended.
JavaScript will suspend the execution of any control flow statements in the try
and/or catch
blocks and will run the finally
block first.
For example, a return within a finally
block would override a return within the preceding try
block, often leading to unexpected behavior.
// We expect this function to return 1;
const foo = function() {
try {
return 1; // 1 is returned but suspended until finally block ends
} catch(err) {
return 2;
} finally {
throw new Error(); // Error was thrown before returning 1
}
}
let foo = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
console.log("hola!");
}
};