可以创建一个内联的 try 但没有 catch,就像所示吗?

huangapple go评论71阅读模式
英文:

Is it possible to create an inline try without a catch like shown

问题

以下是翻译好的部分:

我有一个情况,我想运行可能会出错但我不需要捕获错误的代码。

如果响应不是有效的JSON,那么结果应该是0:

我想使用以下代码:

var overallProgress = try {JSON.parse(text)} ? 0;

是否可以实现上述方式?

或者类似这样:

var overallProgress = try { JSON.parse(text)} catch(error) { 0 };
var overallProgress = try { JSON.parse(text)} catch(error) { overallProgress = 0 };

使用上述代码会出现错误。

我在下面找到了相关的帖子,但没有答案:

https://stackoverflow.com/questions/5764107/is-try-without-catch-possible-in-javascript

对于那些我伤害了眼睛的人:

var overallProgress = 0;
try { overallProgress = JSON.parse(text).overallProgress }
catch(error) { overallProgress = 0 };
英文:

I have this case where I want to run code that may have an error but I don't need to catch it.

If the response is not valid JSON then the result should be 0:

I'd like to use this code:

var overallProgress = try {JSON.parse(text)} ? 0; 

Is it possible to the above?

Or something like this:

var overallProgress = try { JSON.parse(text)} catch(error) { 0 }; 
var overallProgress = try { JSON.parse(text)} catch(error) { overallProgress = 0 }; 

There are errors using the code above.

I found this related post below but no answer.

https://stackoverflow.com/questions/5764107/is-try-without-catch-possible-in-javascript

For anyone whose eyes I've hurt:

var overallProgress = 0; 
try { overallProgress = JSON.parse(text).overallProgress } 
catch(error) { overallProgress = 0 }; 

答案1

得分: 1

不直接支持,但可以使用立即调用函数表达式(IIFE):

const overallProgress = (() => { try { return JSON.parse(text) } catch { return 0 } })();

不过,最好仍然将其格式化为多行:

const overallProgress = (() => {
  try {
    return JSON.parse(text);
  } catch {
    return 0;
  }
})();

除了能够使用 const,它与使用两个赋值语句并没有太大的优势:

let overallProgress;
try {
  overallProgress = JSON.parse(text);
} catch {
  overallProgress = 0;
}

甚至可以简化为:

let overallProgress = 0;
try {
  overallProgress = JSON.parse(text);
} catch {
  /* 忽略:保持 `overallProgress` 的值不变 */
}
英文:

Not directly, no. But you can use an IIFE:

const overallProgress = (() => { try { return JSON.parse(text) } catch { return 0 } })();

I'd still format it as multiple lines though:

const overallProgress = (() => {
  try {
    return JSON.parse(text);
  } catch {
    return 0;
  }
})();

Apart from being able to use const, it doesn't really have an advantage over simply using two assignments:

let overallProgress;
try {
  overallProgress = JSON.parse(text);
} catch {
  overallProgress = 0;
}

or even

let overallProgress = 0;
try {
  overallProgress = JSON.parse(text);
} catch {
  /* ignore: keep `overallProgress` value */
}

huangapple
  • 本文由 发表于 2023年5月26日 08:38:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76336987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定