Python try except异常捕获机制原理解析
作者:落日峡谷 时间:2023-04-12 20:00:35
当你执行大型程序的时候,突然出现exception,会让程序直接停止,这种对服务器自动程序很不友好,而python有着较好的异常捕获机制,不会立刻终止程序。
这个机制就是try-except。
1. 发生异常时可配置备用程序
aa = [1,2,4,5,7,0,2]
for ii in aa:
try:
h = 2/ii
print(h)
except: #发生异常时备用
h = 2/(ii+1)
print(h)
2. 单个异常捕获
dict_ = {}
try:
print(dict_['test'])
print(' --- testing... --- ')
except KeyError as e:
print('--- the error is ---:', e) #单个异常
print(' ---finished!!--- ')
3. 多个异常捕获,循环中
num = [9,7,0,1,4,'16']
for x in num:
try:
print (1/x)
except ZeroDivisionError:
print('error:0做除数!')
except TypeError: # 当报错信息为TypeError,执行下面的语句。
print('error:数值类型错误!')
print(' ---finished!!--- ')
4. 通用异常:Exception,当你不知道异常的种类或者多少异常的时候,可以使用通用异常捕获,同时通用异常可以与特定异常混用。
num = [9,7,0,1,4,'16']
for x in num:
try:
print (1/x)
except ZeroDivisionError:
print('error:0做除数!') #特定异常和Exception混合使用
except Exception as e:
print('the Exception is:',e)
print(' ---finished!!--- ')
5. else语句:在被检测的代码块没有发生异常时执行
dict_ = {'test':'这个地方是哪里?'}
try:
print(dict_['test'])
print(' --- testing... --- ')
except KeyError as e:
print('--- the error is ---:', e) #单个异常
else:
print('没有发生异常!')
print(' ---finished!!--- ')
6. finally语句:不管有没有发生异常都会执行
dict_ = {'test':'这个地方是哪里?'}
try:
print(dict_['test'])
print(' --- testing... --- ')
except KeyError as e:
print('--- the error is ---:', e) #单个异常
else:
print('没有发生异常!')
finally:
print('总可以被执行的语句。。。')
print(' ---finished!!--- ')
来源:https://www.cnblogs.com/qi-yuan-008/p/12708901.html
标签:Python,try,except,异常
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python创建多线程的两种常用方法总结
2023-11-16 16:41:09
python使用正则表达式匹配字符串开头并打印示例
2021-07-02 00:52:13
Python实现求解一元二次方程的方法示例
2023-09-15 03:29:41
分析SQL语句性能3种方法分享
2024-01-14 23:15:57
![](https://img.aspxhome.com/file/2023/1/115311_0s.png)
详解如何在nuxt中添加proxyTable代理
2024-05-10 14:20:29
如何基于Python代码实现高精度免费OCR工具
2022-10-17 07:53:47
python实现class对象转换成json/字典的方法
2021-11-16 00:46:34
asp内置对象Application详解
2007-09-19 12:08:00
mysql 导出CSV文件 并带表头的方法
2024-01-21 20:40:35
简述MySql四种事务隔离级别
2024-01-18 12:52:11
Python实现桌面翻译工具【新手必学】
2021-03-27 08:32:47
使用javascript控制cookie显示和隐藏背景图
2024-04-23 09:33:26
Windows+Anaconda3+PyTorch+PyCharm的安装教程图文详解
2021-07-10 03:34:55
![](https://img.aspxhome.com/file/2023/6/131926_0s.png)
laravel框架关于搜索功能的实现
2024-05-03 15:27:54
彻底理解Python list切片原理
2023-10-19 03:34:43
javascript将数字转换整数金额大写的方法
2024-04-30 10:08:34
python 爬取壁纸网站的示例
2022-07-10 13:29:54
![](https://img.aspxhome.com/file/2023/8/87978_0s.png)
在Python中操作文件之seek()方法的使用教程
2023-08-01 14:58:01
python3实现飞机大战
2023-03-03 00:36:18
![](https://img.aspxhome.com/file/2023/8/87588_0s.jpg)
Git 命令使用技巧提供工作效率
2022-05-11 18:01:33