JS Error Handling with Try...Catch

Try——catch的基本用法

const user={email:`jdoe@gmail.com`}

try{//执行代码

}catch(e){
//若try抛出错误,进入catch

}finally{
  //不管try是否抛出错误,都进入此位置

}

//catch 可以不打断js的读取
console.log('Program continues');

ReferenceError

调用一个未定义的函数

try{
  //Produce a ReferenceError
  myFunction();

  //自己抛出错误
  if(!user.name){
    // throw `User has no name`;  //抛出string
    throw new SyntaxError(`User has no name`);//抛出语法错误

  }

}catch(e){// 一旦有错误就catch
  console.log(e);//包括错误类型
  console.log(e.message); //得到错误的内容
  console.log(e.name); //得到错误类型
  console.log(e instanceof ReferenceError);  //true
  console.log(e instanceof TypeError);  //false
}finally{
  //运行无论是否错误
  console.log('Finally runs reguardless of result...');
}

Typeerror

对null调用methods

try{
  //Produce a Typeerror
  null.myFunction();

  }

}catch(e){// 一旦有错误就catch
  console.log(e);//包括错误类型
  console.log(e.message); //得到错误的内容
  console.log(e.name); //得到错误类型
  console.log(e instanceof ReferenceError); //false
  console.log(e instanceof TypeError);  //true
}finally{
  //运行无论是否错误
  console.log('Finally runs reguardless of result...');
}

SyntaxError

对非公式类字符串使用eval;

try{
  //will produce syntaxError
  console.log(eval(`Hello world`)); //用于计算string的数字

}catch(e){// 一旦有错误就catch
  console.log(e);//包括错误类型
  console.log(e.message); //得到错误的内容
  console.log(e.name); //得到错误类型
  console.log(e instanceof ReferenceError);
  console.log(e instanceof TypeError);
}finally{
  //运行无论是否错误
  console.log('Finally runs reguardless of result...');
}

URIError

try{
  //will produce a URIError
  decodeURIComponent(`%`);

}catch(e){// 一旦有错误就catch
  console.log(e);//包括错误类型
  console.log(e.message); //得到错误的内容
  console.log(e.name); //得到错误类型
  console.log(e instanceof ReferenceError);
  console.log(e instanceof TypeError);
}finally{
  //运行无论是否错误
  console.log('Finally runs reguardless of result...');
}

自定义Error

const user={email:`jdoe@gmail.com`}
try{
  //自己抛出错误
  if(!user.name){
    // throw `User has no name`;  //抛出string
    throw new SyntaxError(`User has no name`);//抛出语法错误
    					//传入的stirng为message
  }

}catch(e){// 一旦有错误就catch
  console.log(`User ERRor: ${e.message}`);
}finally{
  //运行无论是否错误
  console.log('Finally runs reguardless of result...');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值