2019年9月2日 / 15次阅读 / Last Modified 2019年9月3日
语法
Python在加强代码可读性方面真是“不遗余力”。异常处理有else,还有finally,我们需要好好理解这种比较独特的语法结构。
先说一下异常处理的else分支:
有异常,进入except,没异常,进入else。try...语句后面不能直接跟else,必须要有except分支。
再说一下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
前一篇:uuid模块
后一篇:为何要用sys.exit()退出?
©Copyright 麦新杰 Since 2019 Python笔记