[JS] try...catch...finally statement

Article directory

1 description

We can place any code that may cause an exception in the try statement block, and define the method of handling the exception in the catch statement block.

If the code try 语句块in 发生错误, the code will immediately jump from the try statement block to the catch statement block.

If the code is in trythe statement block 没有发生错误, the code in the catch statement block will be ignored.

If finallythe statement block exists, then 无论结果如何finally will be executed.

2 Grammar

try {
    
    
  ... // 可能会发生异常的代码。
} catch (error) {
    
    
  ... // 发生异常时要执行的操作。
} finally {
    
    
  ... // 任何情况下都会执行。
}

3 instances

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript</title>
  </head>
  <body>
    <script>
      try {
    
    
        // 调用一个未定义的变量
        document.write(str);
          
        // 若发生错误,则不会执行以下行
        alert("所有语句都已成功执行。");
          
      } catch (error) {
    
    // 处理错误
        alert("错误信息: " + error.message);
          
      } finally {
    
    // 继续执行下面的代码
        document.write("<p>Hello try catch!</p>");
      }
    </script>
  </body>
</html>

NOTE: Both catch and finally statements are optional, but at least one must be used when using the try statement.

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/126750165