异常
最基本的术语是try/except
从句,将可能触发异常产生的代码放到try
语句块里,而异常处理的代码会在except
语句块里实现。
try:
file = open('test.txt', 'rb')
except IOError as e:
print("An IOError occurred. {}".format(e.args[-1]))
# An IOError occurred. No such file or directory
处理多个异常
第一种方法需要把所有可能发生的异常放到一个元组里。
try:
file = open('test,txt', 'rb')
except (IOError, EOFError) as e:
print("An IOError occurred. {}".format(e.args[-1]))
第二种方法是对每个单独的异常在单独的except语句块中处理。
try:
file = open('test,txt', 'rb')
except IOError as e:
print("An IOError occurred")
raise e
except EOFError as e:
print("An EOF error occurred")
raise e
如果第一个异常没有被第一个except语句块处理,那么就会被下一个语句块处理或者根本不会被处理。
最后一种捕获所有异常
try:
file = open('test,txt', 'rb')
except Exception:
raise
当你们不知道程序抛出什么异常,就可以使用这个。
finally从句
finally从句中的代码不管异常是否触发都将会触发执行,这可以被用在脚本执行之后做清理工作。
try:
file = open('test,txt', 'rb')
except IOError as e:
print("An IOError occurred. {}".format(e.args[-1]))
finally:
print("This would be printed whether or not an exception occurred!")
"""
An IOError occurred. No such file or directory
This would be printed whether or not an exception occurred!
"""
try/else从句
常常想在没有触发异常的时候执行一些代码。这可以很轻松地通过一个else
从句来达到。
try:
print('I am sure no exception is going to occur!')
except Exception:
print('exception')
else:
# 这里的代码只会在try语句里没有触发异常时运行,
# 但是这里的异常将 *不会* 被捕获
print('This would only run if no exception occurs. And an error here '
'would NOT be caught.')
finally:
print('This would be printed in every case.')
# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.
else
从句只会在没有异常的情况下执行,而且它会在finally
语句之前执行。