js中try、catch、finally执行规则的示例分析

这篇文章将为大家详细讲解有关js中try、catch、finally执行规则的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

try:  语句测试代码块的错误,一般把可能会出错的代码放到这里

catch: 只有try里面的代码块发生错误时,才会执行这里的代码,参数err记录着try里面代码的错误信息

finally: 无论有无异常里面代码都会执行

try{
 console.log(0);
 }catch (err){
 console.log(1);
 console.log(hello);
 }finally {
 console.log(2);
 }
 //最后结果分别打印出 0 2
 /*
 try{
 a.b.c();
 }catch (e){
 console.log(1);
 console.log(hello);
 }finally {
 console.log(2);
 }
 */
 //最后结果分别打印出 1 2 报错:hello is not defined
 /*
 try{
 a.b.c();
 }catch (e){
 console.log(1);
 try{
  console.log(hello);
 }catch (e){
  console.log(3);
 }
 }finally {
 console.log(2);
 console.log(word);
 } 
 */
 //最后结果分别打印出 1 3 2 报错:word is not defined
 /*
 try{
 a.b.c();
 }catch (e){
 console.log(1);
 console.log(hello);
 }finally {
 console.log(2);
 console.log(word);
 }*/
 //最后结果分别打印出 1 2 报错:word is not defined

总结:

try里面的代码报错的时候,catch里面的代码才会执行,finally里面的代码永远会执行

catch和finally里面,正常的代码会从上到下顺序执行

如果只是catch里面代码出错,则报catch里面的错误

如果catch和finally都出错则会报finally里面的错误

关于“js中try、catch、finally执行规则的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。