try...except...else...finally

2019年9月2日 / 15次阅读 / Last Modified 2019年9月3日
语法

Python在加强代码可读性方面真是“不遗余力”。异常处理有else,还有finally,我们需要好好理解这种比较独特的语法结构。

先说一下异常处理的else分支:

  • 异常处理的else分支是可选的;
  • 如果要出现else分支,必须在所有except分支之后;
  • 异常处理的else分支不一定会执行,只有在没有发生异常的情况下,才会执行else分支,如果真的发生了异常,else分支就不再执行;

有异常,进入except,没异常,进入else。try...语句后面不能直接跟else,必须要有except分支。

再说一下finally分支:

  • finally分支总是会被执行,不管有无异常发生;
  • 如果异常没有被except分支捕获,或者异常发生在except或else分支内,finally分支执行完毕后,会将此异常抛出;
  • 如果在try语句块内(包括except和else分支),有return,break,continue等语句导致离开,finally分支依然会被执行;

无论如何,finally分支都会被执行。try...语句后面,可以直接跟finally,可以没有except分支。

下面举例说明。这段代码来自Python官方的教材,很有代表性,我加了点注释。

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0  # no exception, run else
executing finally clause  # run finally after else
>>> divide(2, 0)
division by zero!  # catch exception, no else anymore!!
executing finally clause  # run finally after except
>>> divide("2", "1")
executing finally clause  # exception hasn't been catched, but
# exception occured, so no else, only finally, then raise exception.
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

再看一个我自己写的,测试在try中有return语句的例子,finally依然会被执行:

>>> def testtry():
...     try:
...         return
...     except:
...         print('i am except clause')
...     finally:
...         print('finally has to be executed!')
...     return
...
>>> testtry()
finally has to be executed!

再来一个在循环冲continue的case,这次try后面直接跟finally:

>>> for i in range(10):
...     try:
...         if i%2 == 0: print(i)
...         else: continue
...     finally:
...         print('finally...')
...
0
finally...
finally...
2
finally...
finally...
4
finally...
finally...
6
finally...
finally...
8
finally...
finally...

循环中只打印偶数,但是不管是否是偶数,在continue进入下一次循环之前,finally都会被执行。

以上就是对Python中try...except...else...finally语句的学习总结。

-- EOF --

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

留言区

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


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top