JavaScript 抛出异常

摘要: 在本教程中,您将学习如何使用 JavaScript throw 语句抛出异常。

JavaScript throw 语句简介

throw 语句允许您抛出异常。以下是 throw 语句的语法

throw expression;Code language: JavaScript (javascript)

在此语法中,表达式 指定异常的值。通常,您将使用 Error 类或其子类的新的实例。

遇到 throw 语句时,JavaScript 引擎将停止执行并将控制权传递给 调用栈 中第一个 catch 块。如果不存在 catch 块,JavaScript 引擎将终止脚本。

JavaScript 抛出异常示例

让我们看一些使用 throw 语句的示例。

1) 使用 JavaScript throw 语句抛出异常

以下示例使用 throw 语句在 函数 中抛出异常

function add(x, y) {
  if (typeof x !== 'number') {
    throw 'The first argument must be a number';
  }
  if (typeof y !== 'number') {
    throw 'The second argument must be a number';
  }

  return x + y;
}

const result = add('a', 10);
console.log(result);
Code language: JavaScript (javascript)

它是如何工作的。

首先,定义接受两个参数并返回其总和的 add() 函数。add() 函数使用 typeof 运算符检查每个参数的类型,如果类型不是数字,则抛出异常。

其次,调用 add() 函数并将一个字符串和一个数字传递给它。

第三,将结果显示到控制台。

该脚本会导致错误,因为第一个参数 ("a") 不是数字

Uncaught The first argument must be a number

要处理异常,可以使用 try...catch 语句。例如

function add(x, y) {
  if (typeof x !== 'number') {
    throw 'The first argument must be a number';
  }
  if (typeof y !== 'number') {
    throw 'The second argument must be a number';
  }

  return x + y;
}

try {
  const result = add('a', 10);
  console.log(result);
} catch (e) {
  console.log(e);
}
Code language: JavaScript (javascript)

输出

The first argument must be a number

在此示例中,我们将对 add() 函数的调用放在 try 块中。因为 throw 语句中的 表达式 是一个字符串,所以 catch 块中的异常是一个字符串,如输出所示。

2) 使用 JavaScript throw 语句抛出 Error 类的实例

在以下示例中,我们在 add() 函数中抛出 Error 类的实例,而不是字符串;

function add(x, y) {
  if (typeof x !== 'number') {
    throw new Error('The first argument must be a number');
  }
  if (typeof y !== 'number') {
    throw new Error('The second argument must be a number');
  }

  return x + y;
}

try {
  const result = add('a', 10);
  console.log(result);
} catch (e) {
  console.log(e.name, ':', e.message);
}
Code language: JavaScript (javascript)

输出

Error : The first argument must be a numberCode language: JavaScript (javascript)

如输出所示,catch 块中的异常对象具有 nameErrormessage 为我们传递给 Error() 构造函数的值。

3) 使用 JavaScript throw 语句抛出用户定义的异常

有时,您希望抛出自定义错误,而不是内置的 Error。为此,您可以定义一个扩展 Error 类的自定义错误类,并抛出该类的新的实例。例如

首先,定义扩展 Error 类的 NumberError

class NumberError extends Error {
  constructor(value) {
    super(`"${value}" is not a valid number`);
    this.name = 'InvalidNumber';
  }
}Code language: JavaScript (javascript)

NumberError 类的 constructor() 接受在创建该类的新实例时传递给它的值。

NumberError 类的 constructor() 中,我们通过 super 调用 Error 类的构造函数并将字符串传递给它。此外,我们还将错误的名称覆盖为文字字符串 NumberError。如果我们不这样做,NumberErrorname 将为 Error

其次,在 add() 函数中使用 NumberError


function add(x, y) {
  if (typeof x !== 'number') {
    throw new NumberError(x);
  }
  if (typeof y !== 'number') {
    throw new NumberError(y);
  }

  return x + y;
}Code language: JavaScript (javascript)

add() 函数中,如果参数不是有效数字,我们将抛出 NumberError 类的实例。

第三,捕获 add() 函数抛出的异常

try {
  const result = add('a', 10);
  console.log(result);
} catch (e) {
  console.log(e.name, ':', e.message);
}Code language: JavaScript (javascript)

输出

InvalidNumber : "a" is not a valid numberCode language: JavaScript (javascript)

在此示例中,异常名称为 NumberError,消息是我们传递给 NumberError 类的 constructor() 中的 super() 的消息。

总结

  • 使用 JavaScript throw 语句抛出用户定义的异常。
本教程是否有帮助?