编程知识 cdmana.com

Get through the try catch of JavaScript in one minute

Reading guide :
stay Java We use try-cath Do exception handling , alike JavaScript It also provides an exception handling mechanism similar to exception handling , In this section we will talk about JavaScript Exception handling is explained in detail .
 Insert picture description here

var i = {
   
   };   //   Define a variable 
i.func();     //   Call a method that doesn't exist 
console.log("test"); //  If there is an error in the previous code , This code will not execute 

Check the console output

 Insert picture description here

  • From the picture 1 You can see that , A current program occurs TypeError Type of mistake , The error message is “i.func” Not a function , Error code at erroe.html The first 3 That's ok .
  • When an error occurs, only ,JavaScript An error object is thrown , Use try-cath To grab .

 Insert picture description here

      var i = {
   
   };  
    try{
   
              
        i.func();   
        console.log("1");  // An error occurred , The code does not execute 
      } catch(e){
   
   
        console.log(e);  // Grab the wrong object here e
      }
        console.log(" The error was handled ");  // If the error is handled , Code changes will be executed 

Check the console output
 Insert picture description here

  • From the picture 2 We can see that when try When the error code in , utilize catch Exception handling can be done , But when try When an error occurs in a block of code , Later code will not execute , So we should reduce try Block code

版权声明
本文为[osc_ mzickfah]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224105508495u.html

Scroll to Top