Home  >  Article  >  Web Front-end  >  Example analysis of try catch finally in JavaScript exception handling

Example analysis of try catch finally in JavaScript exception handling

黄舟
黄舟Original
2017-10-26 09:41:091670browse

Grammar structure

try catch finally is the ECMAScript-262 third edition standard that provides exception handling mechanism. The grammar structure is as follows:


1 try{
2 //可能会发生的错误代码
3 }
4 catch(error){
5 //错误处理
6 }finally{
7  //无论是否有异常都会执行
8 }

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:


 1 <script> 
 2   function run(){ 
 3       console.log(age); 
 4   } 
 5     run(); 
 6     console.log(&#39;可以输出吗?&#39;);//没有执行 
 7 </script> 
 8  
 9 <script>
 10     console.log(&#39;这是第二个代码块&#39;);//执行了,这是第二个代码块
 11 </script>

On the contrary, the subsequent code will still be executed, such as:


 1 <script> 
 2   function run(){ 
 3       try{ 
 4           console.log(age); 
 5       }catch(error){ 
 6  
 7       } 
 8  
 9   }
 10     run();
 11     console.log(&#39;可以输出吗?&#39;);//可以输出吗?
 12 </script>
 13 
 14 <script>
 15     console.log(&#39;这是第二个代码块&#39;);//这是第二个代码块
 16 </script>

finally statement

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(&#39;finally 执行了&#39;);//finally 执行了        }
    }
    say();

Understand the Error type

When the code is running, an error occurs. An Error object will be created and thrown. 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    to throw an exception to be thrown on behalf of an internal error in the Javascript engine - are created. 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:


##

 1 <script> 
 2     function run() { 
 3         try { 
 4             say("hello word"); 
 5         } 
 6         catch (error) { 
 7             for (var p in error) { 
 8                 document.writeln(error[p]); 
 9             }
 10             //上面可以遍历错误
 11             if (error instanceof EvalError) {
 12                 //如果非法调用了eval()函数,则会抛出EvalError的异常。
 13                 alert("EvalError");
 14             } else if (error instanceof ReferenceError) {
 15                 //错误的引用,此例子是执行到了本步。
 16                 alert("ReferenceError");
 17             } else if (error instanceof RangeError) {
 18                 //数值超出了范围
 19                 alert("RangeError");
 20             } else if (error instanceof SyntaxError) {
 21                 //语法错误,错误发生在eval(),
 22                 alert("SyntaxError");
 23             } else if (error instanceof TypeError) {
 24                 //变量类型不是预期的
 25                 alert("TypeError");
 26             } else if (error instanceof URIError) {
 27                 //错误发生在encodeURI()或decodeURI()中
 28                 alert("URIError");
 29             }
 30         }
 31     }
 32     run();
 33 </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 the throw statement to throw a custom exception such as:


 1 <script> 
 2     function see(){ 
 3         try { 
 4             if(true){ 
 5                 throw new Error("my eroor!"); 
 6             } 
 7  
 8         } catch (error) { 
 9             console.log(error.name );//Error
 10             console.log(error.message);//my eroor!
 11             console.log(error.stack);//Error: my eroor! at see (try.html:12) at try.html:22
 12         }
 13     }
 14     see();
 15 </script>

Exception handling mechanism of Javascript

When an error occurs in the executed javascript code At that time, the js engine will look for the corresponding catch 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 display the error message to the user in different ways (IE displays a yellow triangle pattern in the lower left corner, and Firefix will display in the error console);

window.onerror

Any error that is not handled by tyr-catch will trigger the error event of the window object, such as:


 1 <script> 
 2     window.onerror= function (msg,url,l) 
 3     { 
 4         console.log(msg)//Uncaught ReferenceError: a is not defined 
 5         console.log(url)//http://localhost:63342/person_Project/js_demo/onerror.html 
 6         console.log(l)//17 
 7     } 
 8  
 9     function run(){
 10         console.log(a)
 11     }
 12     run()
 13 </script>

window.onerror event receives three parameters: msg error message, url occurrence The URL of the error page and the line of code where the error occurred.

Front-end code exception monitoring solution

With 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 Example analysis of try catch finally in JavaScript exception handling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn