捕获异常
print('-----test--1---')
try:
print("hehe")
f = open('123.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: '123.txt'
print("hhaha")
except Exception as e:
print(e) # [Errno 2] No such file or directory: '123.txt'
print("出错啦")
print('-----test--2---')
# 文件操作 捕获异常(文件的打开)
# 网络请求 有中断的可能
# 数据库操作(连接的数据库可能会中断)
本文通过一个简单的例子演示了如何使用Python进行异常处理。包括常见的文件读取错误捕获,确保程序在遇到问题时能够正常运行并给出错误提示。
433

被折叠的 条评论
为什么被折叠?



