JavaScript throw 语句

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

在本教程中,您将借助示例了解 JavaScript throw 语句。
    在上一个教程中,您学习了使用 JavaScript try…catch 语句处理异常。try 和 catch 语句以 JavaScript 提供的标准方式处理异常。同时,可以使用 throw 语句传递用户定义的异常。
    在 JavaScript 中,throw 语句处理用户定义的异常。例如,如果某个数字除以 0,并且需要将 Infinity 视为异常,则可以使用 throw 语句来处理该异常。

JavaScript throw 语句

throw 语句的语法是:

  1. throw expression;

在这里,expression 指定异常的值。
    例如,

  1. const number = 5;
  2. throw number/0; // generate an exception when divided by 0

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

JavaScript throw 与 try…catch

try…catch…throw 的语法为:

  1. try {
  2. // body of try
  3. throw exception;
  4. }
  5. catch(error) {
  6. // body of catch
  7. }

注意:当执行 throw 语句时,它退出块并转到 catch 块。并且 throw 语句下面的代码不会执行。

示例 1:try…catch…throw 示例
  1. const number = 40;
  2. try {
  3. if(number > 50) {
  4. console.log('Success');
  5. }
  6. else {
  7. // user-defined throw statement
  8. throw new Error('The number is low');
  9. }
  10. // if throw executes, the below code does not execute
  11. console.log('hello');
  12. }
  13. catch(error) {
  14. console.log('An error caught');
  15. console.log('Error message: ' + error);
  16. }

输出

  1. An error caught
  2. Error message: Error: The number is low

在上述程序中,检查了一个条件。如果数字小于51,则抛出错误。这个错误是使用 throw 语句抛出的。
    throw 语句将字符串 The number is low 指定为表达式。
    注意:您还可以对标准错误使用其他内置错误构造函数: TypeError, SyntaxError, ReferenceError, EvalError, InternalError,和 RangeError。
    例如,

  1. throw new ReferenceError('this is reference error');
重新抛出异常

您还可以在 catch 块中使用 throw 语句来重新引发异常。例如,

  1. const number = 5;
  2. try {
  3. // user-defined throw statement
  4. throw new Error('This is the throw');
  5. }
  6. catch(error) {
  7. console.log('An error caught');
  8. if( number + 8 > 10) {
  9. // statements to handle exceptions
  10. console.log('Error message: ' + error);
  11. console.log('Error resolved');
  12. }
  13. else {
  14. // cannot handle the exception
  15. // rethrow the exception
  16. throw new Error('The value is low');
  17. }
  18. }

输出

  1. An error caught
  2. Error message: Error: This is the throw
  3. 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

相关文章

最新文章

更多