Javascript uses the "try catch" statement to catch exceptions. The syntax is "try {// Code where exceptions may occur} catch(error) {// Operations to be performed when an exception occurs}"; in the try statement block Capture error codes, and define methods for handling exceptions in the catch statement block.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JS Exception Handling
The purpose of exception handling is to capture the code that generates exceptions so that the entire program will not terminate due to exceptions. In JavaScript, you can use the try catch
statement to catch exceptions and handle them accordingly. The syntax format is as follows:
try { // 可能会发生异常的代码 } catch(error) { // 发生异常时要执行的操作 }
We can put any code that may cause exceptions into the try statement block, and define methods for handling exceptions in the catch statement block. If an error occurs in the code in the try statement block, the code will immediately jump from the try statement block to the catch statement block. If no error occurs in the code in the try statement block, the code in the catch statement block will be ignored.
<script> try { var title = "JavaScript"; document.write(title); // 调用一个未定义的变量 document.write(str); // 若发生错误,则不会执行以下行 alert("所有语句都已成功执行。"); } catch(error) { // 处理错误 alert("错误信息: " + error.message); } // 继续执行下面的代码 document.write("<p>Hello World!</p>"); </script>
The running results are as shown below:
When an exception occurs in the code in the try statement block, an Error object will be created and thrown (for example The error in catch(error) in the above code), the object contains two attributes, as shown below:
name: the type of error;
message: Description of the error.
<strong>try catch finally</strong>
Statement
After the try catch statement, you can also add A finally statement block, regardless of whether an error occurs in the code in the try statement block, the code in the finally statement will be executed. The sample code is as follows:
<script> // 接收用户输入的参数 var num = prompt("输入一个 0 到 100 的数字"); // 获取当前时间 var start = Date.now(); try { if(num > 0 && num <= 100) { console.log(Math.pow(num, num)); // 指数幂的基 } else { console.log("输入的值无效!"); } } catch(e) { console.log(e.message); } finally { // 显示执行代码所用的时间 console.log("代码执行花费了:" + (Date.now() - start) + "ms"); } </script>
If we enter a number less than 100, such as 88, the running results are as follows:
1.3015928349429721e+171 代码执行花费了:0ms
If we enter a number greater than 100, such as 123, the running results are as follows:
输入的值无效! 代码执行花费了:0ms
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of What statement does JavaScript use to catch exceptions?. For more information, please follow other related articles on the PHP Chinese website!