JavaScript throw 语句

    在本教程中,您将借助示例了解 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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值