在上一个教程中,您学习了如何使用 JavaScript try..catch 语句处理异常。try 和 catch 语句以 JavaScript 提供的标准方式处理异常。但是,您可以使用 throw 语句来传递用户定义的异常。
在 JavaScript 中,throw 语句处理用户定义的异常。例如,如果某个数字除以 0,并且您需要将 Infinity 视为异常,则可以使用 throw 语句来处理该异常。
JavaScript throw 语句
throw 语句的语法是:
throw expression;
此处,expression 指定异常的值。
例如,
const number = 5;
throw number/0; // generate an exception when divided by 0
注意:表达式可以是 string、boolean、number 或 object 值。
JavaScript throw 与 try...catch 结合使用
try...catch...throw 的语法是:
try {
// body of try
throw exception;
}
catch(error) {
// body of catch
}
注意:当 throw 语句执行时,它会退出该块并转到 catch 块。throw 语句下方的代码不会被执行。
示例 1:try...catch...throw 示例
const number = 40;
try {
if(number > 50) {
console.log('Success');
}
else {
// user-defined throw statement
throw new Error('The number is low');
}
// if throw executes, the below code does not execute
console.log('hello');
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
输出
An error caught Error message: Error: The number is low
在上面的程序中,会检查一个条件。如果数字小于 51,则会抛出错误。该错误使用 throw 语句抛出。
throw 语句将字符串 The number is low 指定为表达式。
注意:您还可以为标准错误使用其他内置错误构造函数:TypeError、SyntaxError、ReferenceError、EvalError、InternalError 和 RangeError。
例如,
throw new ReferenceError('this is reference error');
重新抛出异常
您也可以在 catch 块中使用 throw 语句来重新抛出异常。例如:
const number = 5;
try {
// user-defined throw statement
throw new Error('This is the throw');
}
catch(error) {
console.log('An error caught');
if( number + 8 > 10) {
// statements to handle exceptions
console.log('Error message: ' + error);
console.log('Error resolved');
}
else {
// cannot handle the exception
// rethrow the exception
throw new Error('The value is low');
}
}
输出
An error caught Error message: Error: This is the throw Error resolved
在上面的程序中,throw 语句在 try 块内用于捕获异常。在 catch 块中重新抛出 throw 语句,如果 catch 块无法处理异常,则执行该语句。
此处,catch 块处理了异常,因此没有发生错误。因此,throw 语句没有被重新抛出。
如果 catch 块未处理该错误,则 throw 语句将与错误消息 Uncaught Error: The value is low 一起被重新抛出。