美文网首页
javascript中 throw error 与 throw

javascript中 throw error 与 throw

作者: ZH彪 | 来源:发表于2021-09-13 10:06 被阅读0次

抛出错误一般都是与try catch 同时出现的
先看定义:

throw new Error(error); 这个是创建错误,创造一个错误类型抛出
throw error 这个是抛出错误。

上代码:throw new Error(error)

var a = 5;
try{
   if(a==5){
        //   抛出错误
           throw new Error("loopTerminates"); //Error要大写
     }
}catch(e){
    console.log(e);    //打印出Error对象:Error: loopTerminates
    console.log(e.message); //打印:loopTerminates
}

打印结果:


image.png

throw error:

var a = 5;
try{
   if(a==5){
        //   抛出错误
        throw "loopTerminates";
     }
}catch(e){
    console.log(e);    //打印: loopTerminates
    console.log(e.message); //打印:undefined
}

打印结果:

image.png
转载:https://blog.csdn.net/weixin_40024174/article/details/110877682

相关文章

网友评论

      本文标题:javascript中 throw error 与 throw

      本文链接:https://www.haomeiwen.com/subject/droxgltx.html