可能触发异常产生的代码会放到try语句块里,而处理异常的代码会在except语句块里实现。例如:
try: file = open(‘test.txt’, ‘rb’)except IOError as e: print(‘An IOError occurred. {}’.format(e.args[-1]))
我们可以使用三种方法来处理多个异常。
第一种方法需要把所有可能发生的异常放到一个元组里。像这样:
try: file = open(‘test.txt’, ‘rb’)except (IOError, EOFError) as e: print(“An error occurred. {}”.format(e.args[-1]))
另外一种方式是对每个单独的异常在单独的except语句块中处理。我们想要多少个except语句块都可以:
try: file = open(‘test.txt’, ‘rb’)except EOFError as e: print(“An EOF error occurred.”) raise eexcept IOError as e: print(“An error occurred.”) raise e
最后一种方式会捕获所有异常:
try: file = open(‘test.txt’, ‘rb’)except Exception as e: # Some logging if you want raise e
注意,捕获所有异常可能会造成意外的结果,比如,通常我们使用CTRL+C来终止程序,但如果程序中捕获了所有异常,CTRL+C就无法终止程序了。
包裹到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!”)# Output: An IOError occurred. No such file or directory# This would be printed whether or not an exception occurred!
如果想在没有触发异常的时候执行一些代码,可以使用else从句。
有人也许问了:如果你只是想让一些代码在没有触发异常的情况下执行,为啥你不直接把代码放在try里面呢?回答是,那样的话这段代码中的任意异常都还是会被try捕获,而你并不一定想要那样。
try: print(‘I am sure no exception is going to occur!’)except Exception: print(‘exception’)else: # any code that should only run if no exception occurs in the try, # but for which exceptions should NOT be caught 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. And an error here would NOT be caught# This would be printed in every case.
else从句只会在没有异常的情况下执行,而且它会在finally语句之前执行。