Home > Article > Web Front-end > How does JavaScript handle exceptions? Try method for exception handling
How does JavaScript handle exceptions? This article will give you a brief introduction to a method of handling exceptions in JavaScript: the try...catch...finally statement constructs the throw operator, so that you can understand how it handles exceptions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Let’s take a look at how the try...catch...finally statement block throw handles exceptions:
JavaScript can use try...catch...finally constructor and throw operator to handle exceptions.
This can catch program-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
1. try...catch...finally
Let's take a look at the try...catch...finally block Syntax:
<script type="text/javascript"> <!-- try { // 运行代码 [break;] } catch ( e ) { // 如果发生异常,则运行代码 [break;] } [ finally { // 无论如何,始终执行的代码 // 异常发生 }] //--> </script>
The try block must be followed by a catch block or a finally block (or either). When an exception occurs in the try block, the exception is placed in 'e' and the catch block is executed. The optional finally block is executed unconditionally after the try/catch.
Example:
Example of calling a non-existent function, and this function raised an exception. Let's see how it behaves without try...catch
function myFunc() { var a = 100; alert("变量a的值为 : " + a); }
<p>点击下面查看结果:</p> <form> <input type="button" value="点击我" onclick="myFunc();" /> </form>
Run:
Now let's try catching with try...catch This exception displays a user-friendly message. Users can also suppress this message if they want to hide this error.
function myFunc(){ var a = 100; ry { alert("变量a的值为 : " + a ); } catch ( e ) { alert("错误: " + e.description ); } }
Run:
You can use finally block which will always execute unconditionally after try/catch. Here is an example:
function myFunc() { var a = 100; try { alert("变量a的值为 : " + a); } catch(e) { alert("错误: " + e.description); } finally { alert("Finally块将永远执行!"); } }
Run:
## 2. throw
You can use the throw statement to raise built-in exceptions or custom exceptions, which can later be caught and appropriate actions can be taken. Give an example: How to use throw statementfunction myFunc() { var a = 100; var b = 0; try { if(b == 0) { throw("除以零时出现误差。"); } else { var c = a / b; } } catch(e) { alert("错误: " + e); } }Run:
The above is the detailed content of How does JavaScript handle exceptions? Try method for exception handling. For more information, please follow other related articles on the PHP Chinese website!