javascript 中的 finally 块通过强制执行机制保证代码运行,无论 try 块是否抛出异常或 catch 块是否捕获了错误,finally 内的逻辑都会被触发。具体做法是在 try...catch 结构后追加 finally 代码块,该块会在 try 正常结束、catch 处理完异常或函数提前返回前执行,常用于清理资源或重置状态。

try 块抛出异常时 finally 的执行时机
当 try 块中发生错误并跳转到 catch 块时,finally 会在 catch 块执行完毕后运行。如果 catch 块没有重新抛出异常,程序将继续执行 finally 之后的代码;如果 catch 块抛出了新异常,finally 仍会先于该异常向上传播前执行。

function testException() {
try {
console.log('Try block starts');
throw new Error('Something went wrong');
console.log('This line is skipped');
} catch (e) {
console.log('Catch block handles error:', e.message);
} finally {
console.log('Finally block always runs');
}
console.log('Code after try-catch-finally');
}
testException();预期输出:
Try block starts
Catch block handles error: Something went wrong
Finally block always runs
Code after try-catch-finally
立即学习“Java免费学习笔记(深入)”;
try 块正常返回时 finally 的执行顺序
当 try 块中没有异常且包含 return 语句时,finally 会在返回值计算之后、实际返回之前执行。这意味着如果在 finally 中修改了返回值对应的变量或对象属性,这些修改会影响最终返回给调用者的结果,但直接 return 一个新值会覆盖之前的返回意图。

function testReturn() {
let result = 'original';
try {
console.log('Try block executes normally');
return result;
} finally {
console.log('Finally block modifies result before return');
result = 'modified';
}
}
console.log(testReturn());预期输出:
Try block executes normally
Finally block modifies result before return
modified
finally 块中 return 对主流程的影响
如果在 finally 块中使用 return 语句,它会直接终止 try 或 catch 块的执行流程,并作为整个 try...catch...finally 结构的最终返回值。即使 try 或 catch 中已经定义了返回值,finally 中的 return 也会覆盖它们,导致原返回值被丢弃。
function testFinallyReturn() {
try {
return 'from try';
} catch (e) {
return 'from catch';
} finally {
return 'from finally';
}
}
console.log(testFinallyReturn());预期输出:
from finally


















