Python 中内置了多种异常处理方式。
1 try····except···
a = 10
b = 0
try:
i = a/b
except Exception, e:
print e
>>> integer division or modulo by zero
# 先执行try语句块的内容,若能正常执行,则略过except内容;
# 若try语句块不能正常运行,则紧跟着执行except语句块内容;
a = 10
b = 0
try:
i = a/b
except Exception, e:
print e
finally:
print 101
>>> integer division or modulo by zero
101
# 先执行try语句块的内容,若能正常执行,则略过except内容;
# 若try语句块不能正常运行,则紧跟着执行except语句块内容;
# 最后执行finally语句块;(无论try模块是否正常运行,finally语句块都要执行)
2 assert 语句
>>> assert 3>2, 'error'
>>>
# 3>2 等式成立,不返回任何结果
>>> assert 1>2, 'error'
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\xy.py", line 1, in <module>
assert 1>2, 'error'
AssertionError: error
# 1>2 等式不成立,抛出异常
3 raise 语句
>>> for i in range(5):
if i == 2:
raise ValueError #(ValueError是系统规定的错误类型)
# raise Exception(‘i == 2’) #抛出自定义的错误类型
else:
print i
0
1
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\xy.py", line 4, in <module>
raise ValueError
ValueError
'''
0
1
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\xy.py", line 4, in <module>
raise Exception('i==2')
Exception: i==2
'''