how use const in try catch block [duplicate]

2020-03-09 08:32发布

const is a block level variable so when i try suspect code

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

const is hide in the {}

but

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

not working either because const must be init on declaration.
So how should I using const in try..catch block ?

1条回答
Fickle 薄情
2楼-- · 2020-03-09 08:49

You've hit the nail on the head, because of block scoping you can't declare a const in a try catch block and use it outside the block.

You have 2 3 options:

Use let:

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

Or if there is very little code to come after the try catch block, and it all depends on the success of the try, you can put the rest of the code in the try:

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

EDIT

Option 3 inspired by @Yury Tarabanko's comment: if possible modularise the try catch part into its own function, the output of which should be the value of the new 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
查看更多
登录 后发表回答