Eslint参考手册
规则 | Rules
no-unsafe-finally
"extends": "eslint:recommended"
配置文件中的属性启用此规则。
JavaScript 挂起try
和catch
阻塞的控制流程语句,直到块的执行finally
完成。所以,当return
,throw
,break
,或continue
在使用finally
,内部控制流语句try
和catch
被覆盖,这被认为是意外的行为。如:
// We expect this function to return 1;
(() => {
try {
return 1; // 1 is returned but suspended until finally block ends
} catch(err) {
return 2;
} finally {
return 3; // 3 is returned before 1, which we did not expect
}
})();
// > 3
// We expect this function to throw an error, then return
(() => {
try {
throw new Error("Try"); // error is thrown but suspended until finally block ends
} finally {
return 3; // 3 is returned before the error is thrown, which we did not expect
}
})();
// > 3
// We expect this function to throw Try(...) error from the catch block
(() => {
try {
throw new Error("Try")
} catch(err) {
throw err; // The error thrown from try block is caught and rethrown
} finally {
throw new Error("Finally"); // Finally(...) is thrown, which we did not expect
}
})();
// > Uncaught Error: Finally(...)
// We expect this function to return 0 from try block.
(() => {
label: try {
return 0; // 1 is returned but suspended until finally block ends
} finally {
break label; // It breaks out the try-finally block, before 0 is returned.
}
return 1;
})();
// > 1
规则细节
这条规则不允许return
,throw
,break
,和continue
里面的语句finally
块。它允许间接使用,如in function
或class
定义。
此规则的错误代码示例:
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
return 3;
}
};
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
throw new Error;
}
};
此规则的正确代码示例:
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
console.log("hola!");
}
};
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
let a = function() {
return "hola!";
}
}
};
/*eslint no-unsafe-finally: "error"*/
let foo = function(a) {
try {
return 1;
} catch(err) {
return 2;
} finally {
switch(a) {
case 1: {
console.log("hola!")
break;
}
}
}
};
何时不使用它
如果您想允许finally
块中的控制流操作,则可以关闭此规则。
版本
该规则在 ESLint 2.9.0 中引入。
资源
- Rule source
- Documentation source
规则 | Rules相关

ESLint 是一个代码规范和错误检查工具,有以下几个特性。所有东西都是可以插拔的。你可以调用任意的 rule api 或者 formatter api 去打包或者定义 rule or formatter。任意的 rule 都是独立的。没有特定的 coding style,你可以自己配置。
主页 | https://eslint.org/ |
源码 | https://github.com/eslint/eslint |
发布版本 | 4.12.0 |