实例解析js中try、catch、finally的执行规则
作者:lc5910 时间:2024-04-22 13:25:49
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里面的错误
来源:http://www.cnblogs.com/lc5910/p/6438074.html
标签:js,try,catch,finally
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python yield 的使用浅析
2022-09-30 13:47:01
python Web开发你要理解的WSGI & uwsgi详解
2021-02-04 08:46:38
![](https://img.aspxhome.com/file/2023/1/72981_0s.png)
数字人组件反写[asp组件开发实例2]
2009-06-09 13:15:00
![](https://img.aspxhome.com/file/UploadPic/20093/9/200939182821210s.gif)
Python项目管理Git常用命令详图讲解
2021-01-24 13:41:38
![](https://img.aspxhome.com/file/2023/1/64311_0s.png)
laravel框架关于搜索功能的实现
2024-05-03 15:27:54
ASP和SQL结合处理时间应用
2008-06-09 15:15:00
Python continue语句用法实例
2021-02-16 07:40:00
![](https://img.aspxhome.com/file/2023/1/108061_0s.jpg)
Python元组 tuple的概念与基本操作详解【定义、创建、访问、计数、推导式等】
2022-12-08 10:14:45
python web框架学习笔记
2022-09-30 07:46:38
![](https://img.aspxhome.com/file/2023/0/124680_0s.jpg)
Go语言break跳转语句怎么使用
2024-05-28 15:37:12
![](https://img.aspxhome.com/file/2023/7/123877_0s.png)
python实现全盘扫描搜索功能的方法
2022-10-29 14:43:57
python实现测试工具(一)——命令行发送get请求
2022-04-06 03:49:00
简化SQL Server备份与还原到云工作原理及操作方法
2024-01-18 14:27:36
![](https://img.aspxhome.com/file/2023/2/91202_0s.png)
MySQL存储过程的查看与删除实例讲解
2024-01-23 06:14:11
![](https://img.aspxhome.com/file/2023/6/113996_0s.jpg)
Javascript 中 String.replace( ) 的妙用
2008-08-05 18:08:00
asp.net php asp jsp 301重定向的代码(集合)
2023-11-14 15:02:06
Python格式化字符串f-string的使用教程
2023-10-07 22:33:29
python生成密码字典详解
2021-10-07 20:04:45
![](https://img.aspxhome.com/file/2023/0/105370_0s.png)
php5.4以下版本json不支持不转义内容中文的解决方法
2023-07-02 17:10:45
Python实现构建一个仪表板的示例代码
2023-10-03 11:53:27
![](https://img.aspxhome.com/file/2023/8/62258_0s.gif)