JavaScript throw 语句

x33g5p2x  于2022-04-27 转载在 Java  
字(1.9k)|赞(0)|评价(0)|浏览(232)

在本教程中,您将借助示例了解 JavaScript throw 语句。
    在上一个教程中,您学习了使用 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

注意:表达式可以是字符串、布尔值、数字或对象值。

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 块中用于捕获异常。throw 语句在 catch 块中再次出现,如果 catch 块无法处理异常,就会执行该语句。
    在这里,catch 块处理异常,没有错误发生。因此,throw 语句不需要再次出现。
    如果错误没有被 catch 块处理,throw 语句将被重新调用,并显示错误消息 Uncaught Error: The value is low 。

上一教程 :JS try…catch…finally                                          下一教程 :JS Modules

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/throw

相关文章

微信公众号

最新文章

更多