try/except语句:
python中的try语句可以让程序在出现异常的时候不终止继续执行。
for i in [-1, 0, 1, 2, 3]:
try:
print 100/i
except:
pass
执行结果:
-100
100
50
33
可见i=0时出现的异常被略过了。
try语句必须与except或finally一起使用,except用于对异常进行处理,例如打印一些有用的信息:
for i in [-1, 0, 1, 2, 3]:
try:
print 100/i
except:
print 'divided by zero!'
执行结果:
-100
divided by zero!
100
50
33
except还可以分别对不同的错误类进行处理,例如:
for i in [-1, 0, 1, 2, '']:
try:
print 100/i
except ZeroDivisionError:
print 'divided by zero!'
except:
print 'other error!'
python提供了很多的错误类,详情可见我是爱哭鬼的博客。如果想知道错误信息和错误类型,可以用下面的方法:
for i in [-1, 0, 1, 2, '']:
try:
print 100/i
except Exception, e:
print repr(e)
执行结果:
-100
ZeroDivisionError('integer division or modulo by zero',)
100
50
TypeError("unsupported operand type(s) for /: 'int' and 'str'",)
如果想要得到像不加try语句时得到的回溯信息,可以添加traceback模块:
import traceback
for i in [-1, 0, 1, 2, '']:
try:
print 100/i
except Exception, e:
print traceback.print_exc()
执行结果:
-100
Traceback (most recent call last):
File "test.py", line 5, in <module>
print 100/i
ZeroDivisionError: integer division or modulo by zero
None
100
50
Traceback (most recent call last):
File "test.py", line 5, in <module>
print 100/i
TypeError: unsupported operand type(s) for /: 'int' and 'str'
None
try/finally语句
在使用try语句后,如果某条语句出现异常,则它后面的语句不会被执行,程序直接跳到try之外的语句继续运行。finally语句的作用在于,无论try中的语句是否出现异常,finally中的语句一定会被执行,例如:
for i in [-1, 0, 1, 2, '']:
try:
print 100/i
print "will not be excuted if exception"
except:
pass
finally:
print "always be excuted"
执行结果:
-100
will not be excuted if exception
always be excuted
always be excuted
100
will not be excuted if exception
always be excuted
50
will not be excuted if exception
always be excuted
always be excuted
raise语句
raise语句用于引发异常,使用时后面跟引发的异常的名称,具体异常类见上面的链接。此时会创建一个该异常类的对象,可以用你想打印的异常信息对该对象进行初始化,例如:
a = 'Hello'
if a == 'Hello':
raise TypeError('test the raise statement!')
执行结果:
Traceback (most recent call last):
File "test.py", line 6, in <module>
raise TypeError('test the raise statement!')
TypeError: test the raise statement!