common exception errors:
IOError | if the file can not be opened |
---|---|
ImportError | if python can not find the module |
ValueError | raise whene a build-in operation or functions receive an argument that has the right type but an inapproriate value |
KeyboardInterupt | raised when the user hits the interrupt key |
EOFError | raised when one of the built-n function(intput() or raw_input()) hits an end of file condition without reading any data |
ZeroDivionError | dividion by zero |
try :
...
except Exception,e:
...
显然,在上面的代码中我并没有对aa 赋值,运行结果:
Traceback (most recent call last):
File "/home/fnngj/py_se/tryy.py", line 3, in <module>
print aa
NameError: name 'aa' is not defined
虽然,我知道print 语句是可能会抛一个NameError 类型的错误,虽然接收了这个类型错误,但我不知道具体的错误提示信息是什么。那么,我能不能把错误信息打印出来呢?当然可以:
try:
print aa
except NameError, msg:
print msg
我们在接收错误类型的后面定义一个变量msg用于接收具体错误信息, 然后将msg接收的错误信息打印。再来运行程序:
name 'aa' is not defined
现在只打印了一行具体错误信息。
try...finally...
try...finally...子句用来表达这样的情况:
我们不管线捕捉到的是什么错误,无论错误是不是发生,这些代码“必须”运行,比如文件关闭,释放锁,把数据库连接返还给连接池等。
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
...$ python tryf.py
abc
efg
^CCleaning up...closed the file
Traceback (most recent call last):
File "tryy.py", line 18, in <module>
time.sleep(2)
KeyboardInterrupt
我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭
同时执行多个异常的catch: