如何在 try catch 块中使用 const [重复]

问题描述 投票:0回答:1

const 是一个块级变量,所以当我尝试可疑代码时

try{
   const foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}

const 隐藏在

{}

但是

const foo ;
try{
    foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}

也不起作用,因为

const
必须在声明时初始化。
那么我应该如何在
const
块中使用
try..catch
呢?

编辑2024年
解决方案:我可以使用

var
,问题就解决了

javascript node.js syntax ecmascript-6
1个回答
44
投票

你已经击中要害了,由于块作用域,你不能在 try catch 块中声明

const
并在块外使用它。

您有 2 3 个选择:

使用

let

let foo;
try{
    foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}

或者,如果 try catch 块之后的代码很少,并且这一切都取决于

try
的成功,您可以 将其余代码放入
try

try{
    const foo = bar[global.name].foofoo[global.name2];
    return foo;
}catch (err){
    console.log(error(err.message));
}

编辑

选项 3 受到 @Yury Tarabanko 评论的启发:如果可能的话 将 try catch 部分模块化为自己的函数,其输出应该是新的值

const
:

function trycatch() {
    try {
        return bar[global.name].foofoo[global.name2];
    } catch (err) {
        console.log(error(err.message));
        return undefined; // or whatever you want
    }
}

const foo = trycatch(); // === bar[global.name]... if succeeded, otherwise === the return value from the catch block
© www.soinside.com 2019 - 2024. All rights reserved.