JavaScript try...catch...finally 语句

x33g5p2x  于2022-04-25 转载在 Java  
字(2.2k)|赞(0)|评价(0)|浏览(506)

在本教程中,您将借助示例了解在 JavaScript 中处理异常的 try…catch…finally 语句。
    try、catch 和 finally 块用于处理异常(一种错误)。在了解它们之前,您需要了解编程中的错误类型。

错误类型

在编程中,代码中可能存在两种类型的错误:
    语法错误:语法错误。例如,如果你写 consol.log(‘your result’); ,上面的程序会抛出一个语法错误。上面代码中的 console 拼写错误。
    运行错误:此类错误发生在程序执行期间。例如,调用无效的函数或变量。
    这些在运行时发生的错误称为异常。现在,让我们看看如何处理这些异常。

JavaScript try…catch 语句

try…catch 语句用于处理异常。它的语法是:

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

主代码在 try 块中。在执行 try 块时,如果出现任何错误,它将转到 catch 块。catch 块根据 catch 语句处理错误。
    如果没有发生错误,则执行 try 块内的代码,并跳过 catch 块。

示例 1:显示未声明的变量
  1. // program to show try...catch in a program
  2. const numerator= 100, denominator = 'a';
  3. try {
  4. console.log(numerator/denominator);
  5. // forgot to define variable a
  6. console.log(a);
  7. }
  8. catch(error) {
  9. console.log('An error caught');
  10. console.log('Error message: ' + error);
  11. }

输出

  1. NaN
  2. An error caught
  3. Error message: ReferenceError: a is not defined

在上述程序中,a 变量未定义。当您试图打印 a 变量时,程序会抛出一个错误。该错误被捕获在 catch 块中。

JavaScript try…catch…finally 语句

你也可以用 try…catch…finally 语句处理异常。当代码成功运行或发生错误时 finally 块都会执行。
    try…catch…finally 块的语法是:

  1. try {
  2. // try_statements
  3. }
  4. catch(error) {
  5. // catch_statements
  6. }
  7. finally() {
  8. // codes that gets executed anyway
  9. }
示例 2:try…catch…finally 示例
  1. const numerator= 100, denominator = 'a';
  2. try {
  3. console.log(numerator/denominator);
  4. console.log(a);
  5. }
  6. catch(error) {
  7. console.log('An error caught');
  8. console.log('Error message: ' + error);
  9. }
  10. finally {
  11. console.log('Finally will execute every time');
  12. }

输出

  1. NaN
  2. An error caught
  3. Error message: ReferenceError: a is not defined
  4. Finally will execute every time

在上面的程序中,发生了一个错误,该错误被 catch 块捕获。finally 块将在任何情况下执行(如果程序成功运行或出现错误)。
    注意:您需要在 try 语句之后使用 catch 或 finally 语句。否则,程序将抛出一个错误 Uncaught SyntaxError: Missing catch or finally after try 。

JavaScript try…catch 与 setTimeout

如果异常发生在 “timed” 代码中,如 setTimeout(),try…catch 将不会捕获该异常。例如,

  1. try {
  2. setTimeout(function() {
  3. // error in the code
  4. }, 3000);
  5. } catch (e) {
  6. console.log( "won't work" );
  7. }

以上 try…catch 将不起作用,因为引擎已经离开了 try…catch 构造并且函数稍后执行。
    try…catch 块必须位于函数内,才能捕获定时函数内的异常。例如,

  1. setTimeout(function() {
  2. try {
  3. // error in the code
  4. } catch {
  5. console.log( "error is caught" );
  6. }
  7. }, 3000);

您还可以将 throw 语句与 try。。。catch 语句使用用户定义的异常。例如,某个数字被 0 除。如果您想将 Infinity 视为程序中的一个错误,则可以使用 throw 语句抛出用户定义的异常来处理该条件。
    您将在下一个教程中了解 JavaScript throw 语句。

上一教程 :JS Symbols                                          下一教程 :JS throw

参考文档

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

相关文章

最新文章

更多