如何在try catch块中使用const [英] how use const in try catch block
问题描述
const是一个块级变量,所以当我尝试怀疑代码时
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隐藏在 {}
但是
const foo ;
try{
foo = bar[global.name].foofoo[global.name2];
}catch (err){
console.log(error(err.message));
}
无效,因为 const
必须是声明初始化。
所以我应该如何在 try..catch $ c $中使用
const
c>阻止?
not working either because const
must be init on declaration.
so how should I ussing const
in try..catch
block ?
推荐答案
你已经击中了头部,因为阻挡范围你无法宣布一个<在try块中code> const 并在块外使用它。
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.
你有 2 3个选项:
使用让
:
Use let
:
let foo;
try{
foo = bar[global.name].foofoo[global.name2];
}catch (err){
console.log(error(err.message));
}
或者如果try catch块之后的代码很少,和一切都取决于尝试
的成功,你可以将其余的代码放在中试试
:
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));
}
编辑
选项3的灵感来自@Yury Tarabanko的评论:如果可能的话将try catch部分模块化为自己的函数,其输出应该是新<$ c $的值c> const :
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
这篇关于如何在try catch块中使用const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!