Why does a return in `finally` override `try`?(为什么`finally`中的返回会覆盖`try`?)
问题描述
try/catch 块中的 return 语句如何工作?
How does a return statement inside a try/catch block work?
function example() {
try {
return true;
}
finally {
return false;
}
}
我希望这个函数的输出是 true,但实际上它是 false!
I'm expecting the output of this function to be true, but instead it is false!
推荐答案
最后 always 执行.这就是它的用途,这意味着它的返回值会在您的情况下使用.
Finally always executes. That's what it's for, which means its return value gets used in your case.
您需要更改您的代码,使其更像这样:
You'll want to change your code so it's more like this:
function example() {
var returnState = false; // initialization value is really up to the design
try {
returnState = true;
}
catch {
returnState = false;
}
finally {
return returnState;
}
}
一般来说,你永远不想在一个函数中有多个 return 语句,这样的事情就是原因.
Generally speaking you never want to have more than one return statement in a function, things like this are why.
这篇关于为什么`finally`中的返回会覆盖`try`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么`finally`中的返回会覆盖`try`?
基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
