JS学习笔记 之 try...catch

try{}catch(e){}finally{} 处理流程:

  a. 正常执行try内的代码

  b. 遇到错误,停止执行后续try内的代码,并跳转到catch部分,同时将错误信息封装到error对象中传入catch

    i. 执行catch部分代码,可利用传入的error对象,打印错误信息(通过try catch 捕捉到的错误信息不会抛出到控制台影响后续代码的执行)

    ii. 继续执行后面的语句

  c. try内没有遇到错误,跳过catch块,正常执行后续的语句

error.name对应的六种错误类型

EvalError eval()的使用与定义不一致
RangeError 数值越界
RerfernceError 非法或不能识别的引用数值
SyntaxError 语法解析错误
TypeError 操作数类型错误
URIError UIR处理函数使用不当

1. try...catch块内有错的情况  

1  try{
2             console.log('a');
3             console.log(b);  //出错,从这里开始往后的所有try内的语句都不会被执行,直接跳转执行catch部分
4             console.log('c');
5 
6  }catch(e){    // error error.name error.message等 --> 封装到error对象中传入
            console.log(e.name + ' : ' + e.message );
7 
8  }
9  console.log('d');  //try catch 之外的其他的代码会继续正常执行



//打印 :

 当try内部不止一个错误时,遇到第一个错误就停止执行后续try内部的代码 try{

            console.log('a');
            console.log(b);            
            console.log(c);

        }catch(e){ // error error.name error.message等 --> 封装到error对象中传入
            console.log(e.name + ' : ' + e.message );

        }
        console.log('d');

//同样打印
  

2. try...catch块内无错的情况

 try{
            console.log('a');
            console.log('b');
            console.log('c');

        }catch(e){

        }
        console.log('d');  

//正常执行,打印 a b c d

 2019-11-05 15:50:34

原文地址:https://www.cnblogs.com/seveinn/p/11798631.html