
JavaScript 抛出异常
在本教程中,您将学习如何使用 JavaScript throw 语句抛出异常
在本教程中,您将学习如何使用 JavaScript throw 语句抛出异常。
JavaScript throw 语句介绍
throw 语句允许您抛出异常。下面是 throw 语句的语法:
throw expression;在此语法中,expression 指定异常的值。通常,您会使用 Error 类或其子类的实例作为异常的值。
遇到 throw 语句时,JavaScript 引擎停止执行并将控制权传递给调用堆栈第一个catch 块。如果不存在 catch 块,JavaScript 引擎将终止脚本运行。
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);
代码是如何运行的。
- 首先,定义接受两个参数并返回它们之和的
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);
}
输出:
The first argument must be a number在此示例中,我们将 add() 函数的调用放在一个 try 块中。因为 throw 语句的 expression 是一个字符串,所以 catch 块中的异常是一个字符串,如输出所示。
JavaScript throw语句抛出 Error 类的实例
在下面的例子中,我们抛出一个 Error 类的实例而不是 add() 函数中的一个字符串;
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);
}
输出:
Error : The first argument must be a number
如输出所示,catch 块中的异常 Error 对象具有我们传递给 Error() 构造函数的name 和 message 属性。
JavaScript throw 语句抛出自定义异常
有时,您想抛出自定义错误而不是内置的 Error 。 为此,您可以自定义错误类来扩展 Error 类并抛出类的实例。例如:
首先,定义 NumberError 扩展 Error 类:
class NumberError extends Error {
constructor(value) {
super(`"${value}" is not a valid number`);
this.name = 'InvalidNumber';
}
}NumberError 类的 constructor() 接受一个参数,在你创建类的实例时。
在 NunberError 类的 constructor() ,我们调用 Error 类的构造函数,并向其传递一个字符串。此外,我们将 Error 的 name 属性重写为另一个值。如果不这样做的话,NumberError 的 name属性值是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;
}在 add() 函数中,如果 Number 参数不是有效的数字,我们将抛出 NumberError 类的一个实例。
最后,捕获 add() 函数抛出的异常:
try {
const result = add('a', 10);
console.log(result);
} catch (e) {
console.log(e.name, ':', e.message);
}输出:
NumberError : "a" is not a valid number在这个例子中,异常名称是 NumberError ,消息是我们在 NumberError 类的 constructor() 函数传递给 Error 父类 super() 函数的那个。
结论
使用 JavaScript throw语句抛出用户自定义的异常。












