使用方法直接跳看:推荐使用的异常处理流程;推荐的内建函数的封装函数
异常处理必要性
为了保证程序的健壮性,将可能出现异常退出的代码用try……except来处理
捕获异常的各种方法
1.捕获所有异常
print "\r\n=======try-except========="
try:
open('unexistFile')
except:
print "failed to open."
2.捕获特殊异常,如ctrl+c等
KeyboardInterrupt和SystemExit,是与Exception平级的异常。
print '\r\n======try-except (KeyboardInterupt, SystemExit)======'
try:
while 1:
pass
except (KeyboardInterrupt, SystemExit):#ctrl+c等导致app退出异常
print 'app will exit, handle app exitence.'
3.捕获具体异常,1/0等
print "\r\n======try-except ZeroDivisionError,e======="
try:
1/0 #除数为零
except ZeroDivisionError, e:
print 'ZeroDivisionError:',e
4.捕获多个具体的异常
#try-except (E1, E2,……En)[,e]:捕获多个异常
print '\r\n======try-except (E1, E2,……En)[,e]======'
try:
1/0
except (NameError,ZeroDivisionError),e:
print repr(e)
5.待追加
简单示例代码
#ex_except.py
def dumpFile_withExcept(path):
try:
f = file(path)
print 'Succeed open file'
f.close()
except:
print 'Failed open file, file not exists.'
return False
return True
def dumpFile_nonExcept(path):
f = file(path)
f.close()
#test
dumpFile_withExcept('non-exist.txt')
dumpFile_nonExcept('non-exist.txt')
编译执行