1.else的用法
对try...except的补充:
else
子句的使用比在子句中添加其他代码更好,try
因为它避免了意外捕获由try
... except
语句保护的代码未引发的异常。
for arg in sys.argv[1:]: try: f = open(arg, 'r') except OSError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close()
2.finally用法
try
语句有一个可选finally子句,用于定义在所有情况下都必须执行的finally操作
try: raise KeyboardInterrupt finally: print('Goodbye, world!') Goodbye, world! KeyboardInterrupt Traceback (most recent call last): File "<stdin>", line 2, in <module>
如果存在finally
子句,则该finally
子句将作为try
语句完成之前的最后一项任务执行。finally
无论该try
语句是否产生异常,该子句都会运行。
以下几点讨论了发生异常时更复杂的情况:
-
如果在执行该
try
子句期间发生异常,则该异常可以由except
子句处理。如果该异常未由except
子句处理,finally
则在执行该子句后将重新引发该异常。 -
执行
except
orelse
子句期间可能会发生异常。同样,在finally
执行该子句之后,将重新引发异常。 -
如果
try
语句到达break
,continue
或return
语句时,finally
条款将在<try or else or except的>break
,continue
或return
语句之前执行。 -
如果
finally
子句包含一条return
语句,则该finally
子句的return
语句将在<try or else or except的>子句中的return语句之前执行,所以事实上执行了的是finally的return,而不是在<try or else or except>中执行return
语句。
案例1.
>>> def bool_return(): ... try: ... return True ... finally: ... return False ... >>> bool_return() False
案例2.
def bool_return(): try: raise Exception except Exception: return True finally: return False print(bool_return())
False
案例3.
>>> 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 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'