发布于 

Python错误与异常

错误与异常

1
2
3
4
5
6
7
8
9
10
# 捕获异常
try:
print("------test-------1--------")

f = open("123.txt", "r") # 要打开的文件不存在

print("------test-------2--------")

except IOError:
pass # 捕获异常后,执行的代码

异常类型想要被捕获,需要一致

获取错误描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 捕获异常
try:
print("------test-------1--------")

f = open("test1.txt", "r") # 要打开的文件不存在

print("------test-------2--------")
print(num)
except (IOError,NameError) as result:
print("产生错误了!")
print(result)

'''
结果:
------test-------1--------
------test-------2--------
产生错误了!
name 'num' is not defined
'''

捕获所有异常

Exception可以承接任何异常


本站由 Cccccpg 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。