Python try-except-else-finally的具体使用
作者:cinderamanda 时间:2022-10-18 14:31:45
try-except
作用:处理异常情况
用法:try:
后面写正常运行的代码,except + 异常情况:
后面写对异常情况的处理
示例:
try:
num = int(input("Please input a number:\n"))
print(42 / num)
except ZeroDivisionError: #except后为错误类型
print("Divided by zero!")
except ValueError: #可以有多个错误类型
print("Wrong value!")
运行结果:
注意:调用try语句时,try后的所有错误都将被捕捉,一旦遇到错误,立即跳到except语句块,错误之后的语句不再执行
def division(DivideBy):
return 42 / DivideBy
try:
print(division(1))
print(division(0))
print(division(7))
except ZeroDivisionError:#except后写错误类型
print("Divided by zero!")
运行结果:
try-except-else
和try-except类似,不过如果程序没有错误,也就是没有跳到except语句块,则执行else语句块,如果程序发生错误,即跳到except语句块,则直接跳过else语句块
示例程序:
def division(DivideBy):
return 42 / DivideBy
try:
num = int(input("Please input a integer:\n"))
print(division(num))
except ZeroDivisionError:#except后写错误类型
print("Divided by zero!")
except ValueError:
print("Wrong input!")
else:
print("No error. Good job!")
运行结果:
try-finally
finally:
无论try后是否有异常,都要执行
def division(DivideBy):
return 42 / DivideBy
try:
num = int(input("Please input a integer:\n"))
print(division(num))
except ZeroDivisionError: # except后写错误类型
print("Divided by zero!")
except ValueError:
print("Wrong input!")
else:
print("No error. Good job!")
finally:
print("Finished")
运行结果:
来源:https://blog.csdn.net/cinderamanda/article/details/119989374
标签:Python,try-finally,try-except-else,try-except
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python3中setuptools、Pip安装教程
2023-12-30 11:49:40
Python基础学习之反射机制详解
2023-02-15 11:02:01
mysql数据表和数据表关联
2010-12-03 16:00:00
使用Python对Access读写操作
2021-01-07 04:20:36
Ubuntu下Python+Flask分分钟搭建自己的服务器教程
2023-11-12 04:37:43
![](https://img.aspxhome.com/file/2023/2/63182_0s.jpg)
使SQL用户只能看到自己拥有权限的库(图文教程)
2024-01-27 11:07:27
![](https://img.aspxhome.com/file/2023/6/129296_0s.png)
Python写出新冠状病毒确诊人数地图的方法
2022-09-28 06:15:13
![](https://img.aspxhome.com/file/2023/3/133433_0s.png)
谈谈为什么你的 JavaScript 代码如此冗长
2024-04-17 09:50:07
Python实现的查询mysql数据库并通过邮件发送信息功能
2024-01-21 11:51:36
PHP+MYSQL不恶补十句话
2009-12-02 10:09:00
python进阶教程之词典、字典、dict
2022-10-10 10:41:36
springboot整合单机缓存ehcache的实现
2023-11-09 15:27:24
![](https://img.aspxhome.com/file/2023/7/133217_0s.png)
Oracle使用触发器和mysql中使用触发器的案例比较
2024-01-26 02:46:49
pycharm下打开、执行并调试scrapy爬虫程序的方法
2022-08-07 09:30:52
![](https://img.aspxhome.com/file/2023/5/66785_0s.png)
python中使用多线程改进flask案例
2022-11-07 05:44:55
Python自动化办公之群发邮件案例详解
2023-09-08 17:10:36
![](https://img.aspxhome.com/file/2023/9/120929_0s.jpg)
在Python的Flask中使用WTForms表单框架的基础教程
2023-05-10 05:20:08
![](https://img.aspxhome.com/file/2023/6/90746_0s.png)
php+mysql删除指定编号员工信息的方法
2024-06-05 09:40:28
HTML5实现留言和回复页面样式
2024-04-18 10:32:20
Python selenium实现断言3种方法解析
2023-06-06 06:08:53