Home >Web Front-end >JS Tutorial >js exception handling try catch finally explanation
try catch finally is the ECMAScript-262 third edition standard that provides exception handling mechanism. The grammar structure is as follows:
try{ //可能会发生的错误代码 } catch(error){ //错误处理 }finally{ //无论是否有异常都会执行 }
Grammar and Like most languages such as java.net, if the try{} code block catches an exception, the catch block will get an error message object (an instance of Error).
We should put the code that may cause errors in the try block, and error handling in the catch block; in js, if an error occurs in the 3f1c4e4b6b16bbbd69b2ee476dc4f83a2cacc6d41bbb37262a98f745aa00fbf0 code block and there is no If the exception is caught, the subsequent code of the current 3f1c4e4b6b16bbbd69b2ee476dc4f83a code block will not be executed, but it will not affect other 3f1c4e4b6b16bbbd69b2ee476dc4f83a2cacc6d41bbb37262a98f745aa00fbf0 code blocks such as:
<script> function run(){ console.log(age); } run(); console.log('可以输出吗?');//没有执行 </script> <script> console.log('这是第二个代码块');//执行了,这是第二个代码块 </script>
On the contrary, the subsequent code will still be executed, such as:
<script> function run(){ try{ console.log(age); }catch(error){ } } run(); console.log('可以输出吗?');//可以输出吗? </script> <script> console.log('这是第二个代码块');//这是第二个代码块 </script>
If there is a finally code block, then no matter what The code in the reason will be executed, even if there is a return statement in the catch statement, the following code:
function say() { try { console.log(age) return; } catch (erroe) { console.log(erroe.message);//age is not defined return; } finally { console.log('finally 执行了');//finally 执行了 } } say();
Understand the Error type
When an error occurs when the code is running, an Error object will be created and its Throw, this object contains error description information.
For example, in the try...catch(error){...} statement, Error is an object thrown by the Error type. The object has three basic attributes: name, error name, message Error information, stack error stack information;
There are many types of errors that may occur during the period of execution code, so Error dispatched several sons such as:
# E error error. See, if there are any, they are thrown by the browser; the main purpose of this base type is for developers to throw custom errors.
Evalerror Create an Error instance to indicate the reason for the error: it is related to Eval ().
InternalError to create an example of an internal error that represents the internal error of the JavaScript engine. Such as: "Too much recursion".
Rangeerror created an ERROR instance to indicate the reason for the error: numerical variables or parameters exceeded its effective range.
ReferenceError Create an error instance to indicate the cause of the error: invalid reference.
Syntaxerror Create an ERROR instance to indicate the reason why the error is: evac () the syntax error occurred during the parsing code.
Typerror Create an ERROR instance, indicating the cause of the error: variables or parameters are not effective types.
URIError Create an error instance to indicate the cause of the error: the parameters passed to encodeURI() or decodeURl() are invalid.
Error is the base class. Other error types are inherited from the Error type, so the subclasses also have three basic attributes: name, error name, message, and stack.
With these error types, we can write code like this to specifically handle a certain type of exception by judging the type of exception, such as:
##
<script> function run() { try { say("hello word"); } catch (error) { for (var p in error) { document.writeln(error[p]); } //上面可以遍历错误 if (error instanceof EvalError) { //如果非法调用了eval()函数,则会抛出EvalError的异常。 alert("EvalError"); } else if (error instanceof ReferenceError) { //错误的引用,此例子是执行到了本步。 alert("ReferenceError"); } else if (error instanceof RangeError) { //数值超出了范围 alert("RangeError"); } else if (error instanceof SyntaxError) { //语法错误,错误发生在eval(), alert("SyntaxError"); } else if (error instanceof TypeError) { //变量类型不是预期的 alert("TypeError"); } else if (error instanceof URIError) { //错误发生在encodeURI()或decodeURI()中 alert("URIError"); } } } run(); </script>throw throws a custom error type Syntax: throw exception; exception can be any type of data such as: throw 12345;throw 'hello';throw true;throw {name:'Joel',age:20};Use throw statement To throw a custom exception such as:
<script> function see(){ try { if(true){ throw new Error("my eroor!"); } } catch (error) { console.log(error.name );//Error console.log(error.message);//my eroor! console.log(error.stack);//Error: my eroor! at see (try.html:12) at try.html:22 } } see(); </script>Exception handling mechanism of JavascriptWhen an error occurs in the executed javascript code, the js engine will The corresponding catch will be searched step by step according to the js call stack. If the corresponding catch handler is not found or there is an error or a new error is thrown, the error processing will be handed over to the browser. The browser will use Different ways (IE displays a yellow triangle pattern in the lower left corner, and Firefix will display in the error console) display error messages to the user; window.onerrorAnything that does not pass tyr- The errors handled by catch will trigger the error event of the window object, such as:
<script> window.onerror= function (msg,url,l) { console.log(msg)//Uncaught ReferenceError: a is not defined console.log(url)//http://localhost:63342/person_Project/js_demo/onerror.html console.log(l)//17 } function run(){ console.log(a) } run() </script>window.onerror event receives three parameters: msg error message, url the url of the page where the error occurred, line The line of code where the error occurred. Front-end code exception monitoring solutionWith the error object captured by try catch and window.onerror globally monitoring error events, front-end js code error monitoring becomes too simple
The above is the detailed content of js exception handling try catch finally explanation. For more information, please follow other related articles on the PHP Chinese website!