throw 表达式

JavaScript 语法规定throw是一个命令,用来抛出错误,不能用于表达式之中。

  1. // 报错
  2. console.log(throw new Error());

上面代码中,console.log的参数必须是一个表达式,如果是一个throw语句就会报错。

现在有一个提案,允许throw用于表达式。

  1. // 参数的默认值
  2. function save(filename = throw new TypeError("Argument required")) {
  3. }
  4. // 箭头函数的返回值
  5. lint(ast, {
  6. with: () => throw new Error("avoid using 'with' statements.")
  7. });
  8. // 条件表达式
  9. function getEncoder(encoding) {
  10. const encoder = encoding === "utf8" ?
  11. new UTF8Encoder() :
  12. encoding === "utf16le" ?
  13. new UTF16Encoder(false) :
  14. encoding === "utf16be" ?
  15. new UTF16Encoder(true) :
  16. throw new Error("Unsupported encoding");
  17. }
  18. // 逻辑表达式
  19. class Product {
  20. get id() {
  21. return this._id;
  22. }
  23. set id(value) {
  24. this._id = value || throw new Error("Invalid value");
  25. }
  26. }

上面代码中,throw都出现在表达式里面。

语法上,throw表达式里面的throw不再是一个命令,而是一个运算符。为了避免与throw命令混淆,规定throw出现在行首,一律解释为throw语句,而不是throw表达式。