finally抑制异常raise的情况

2021年5月21日 / 20次阅读 / Last Modified 2021年5月21日
异常处理

不是只有except分支语句可以抑制异常的raise,finally分支语句在某些情况下,也能够抑制异常不要raise出来!

finally是python异常处理块最后执行的部分代码,下面是python官方对finally在re-raise时的一个说明:

The following points discuss more complex cases when an exception occurs:

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

If the finally clause executes a break, continue or return statement, exceptions are not re-raised.

If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.

If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

当有except能够接住某个异常的时候,不会有异常被re-raise;当没有except被执行时,finally执行后,异常会re-raise出来;或者当异常发生在except或else分支中时,这时等同于没有except与承接那个异常,在finally执行后,异常会re-raise。

但是,当在finally中执行break,continue,return的时候,异常不会做re-raise,测试代码:

>>> while True:
...   try:
...     1/0
...   finally:
...     break
...

没有异常出现。。。再来一段测试代码:

>>> for i in range(10):
...   try:
...     1/0
...   finally:
...     print('finally...')
...     continue
...
finally...
finally...
finally...
finally...
finally...
finally...
finally...
finally...
finally...
finally...

Python从3.8开始,才支持finally语句中嵌套continue!

>>> def test():
...   try:
...     1/0
...   finally:
...     print('ready to return...')
...     return
...
>>> test()
ready to return...

依然没有异常出现。。。

-- EOF --

本文链接:https://www.pynote.net/archives/3690

留言区

您的电子邮箱地址不会被公开。 必填项已用*标注


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top