异常处理
try/except从句。
将可能触发异常产生的代码放到try模块里,而处理异常的代码会在except语句块里实现。如:
try:
file=open('test.txt','rb')
except IOError as e:
print('An IOError occured. {}'.format(e.args[-1]))
输出:
An IOError occured. No such file or directory
处理多个异常
try:
file=open('test.txt','rb')
except (IOError,EOFError) as e:
print('An IOError occured. {}'.format(e.args[-1]))
或者:
try:
file=open('test.txt','rb')
except EOFError as e:
print('An IOError occured. {}'.format(e.args[-1]))
raise e
except IOError as e:
print('An IOError occured. {}'.format(e.args[-1]))
raise e
捕获所有异常
try:
file=open('test.txt','rb')
except Exception:
#打印一些异常日日志
raise
finally从句
在上面异常处理语句中,有try从句和except从句,我们还会使用第三个从句就是finally从句。在finally从句中的代码不管异常是否触发都将会被执行。可以被用来在脚本结束执行后做清理工作。
比如:
try:
file=open('test.txt','rb')
except IOError as e:
print('An IOError occured. {}'.format(e.args[-1]))
finally:
print("this would be printed whether or not an error")
输出:
An IOError occured. No such file or directory
this would be printed whether or not an error
try/else从句
如果在异常处理语句中,想让一些代码在没有触发异常的情况下执行,就要使用else从句了,为啥不直接把执行代码放try里呢,是因为如果放在try里这段代码的任何异常也会被try捕获。
比如:
try:
print('I am sure no error')
except:
print('exception')
else:
print("This would be printed if no error")
finally:
print("This would be printed every case")
输出:
I am sure no error
This would be printed if no error
This would be printed every case