You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何throw在箭头函数中必须使用大括号包裹?

箭头函数中throw语句需用大括号的原因

箭头函数存在两种语法形式,这是问题的核心:

  • 简洁体(无大括号):() => 表达式,右侧必须是合法的表达式,JavaScript会自动将该表达式的结果作为函数返回值。
  • 块体(带大括号):() => { 语句 },右侧是代码块,可包含任意数量的语句(如throw、return、变量声明等),需手动编写return来指定返回值(如有需要)。

结合你的代码分析

  1. 正常运行的代码:
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => console.log("it's ok"));

这里console.log("it's ok")是函数调用表达式,符合简洁体的语法要求,因此无需大括号就能正常运行。

  1. 报错的代码:
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => throw new Error("it's not ok"));

throw new Error("it's not ok")是throw语句,不属于表达式范畴,而简洁体仅允许放置表达式,因此这会触发语法错误。

  1. 修复后的代码:
const test = new Promise((resolve, failure) => {
failure("mistake");
});
const handler = test.catch(() => {throw new Error("it's not ok")});

添加大括号后,箭头函数转为块体语法,代码块内可容纳任意语句,throw语句在这里合法,因此代码恢复正常运行。

总结

并非throw“任何情况下都需要大括号”,而是throw作为语句,只能放在箭头函数的块体(带大括号)中;若箭头函数使用简洁体,右侧必须是表达式,而throw不属于表达式,因此必须用大括号包裹成块体才能合法使用。

内容的提问来源于stack exchange,提问作者lome1446

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:31:06