Purpose of else and finally in exception handling
异常处理的
1 2 3 4 5 6 7 8 | try: foo = open("foo.txt") except IOError: print("error") else: print(foo.read()) finally: print("finished") |
和
1 2 3 4 5 6 | try: foo = open("foo.txt") print(foo.read()) except IOError: print("error") print("finished") |
更一般地说,
我们的想法是尽可能减少处理异常的代码。
从马的嘴里:
The use of the
else clause is better than adding additional code to thetry clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by thetry ... except statement.
正如其他两个答案已经说过的那样,
官方的措辞:
When an exception has occurred in the
try clause and has not been handled by anexcept clause (or it has occurred in aexcept orelse clause), it is re-raised after thefinally clause has been executed. Thefinally clause is also executed"on the way out" when any other clause of thetry statement is left via abreak ,continue , orreturn statement.
*上下文管理器(
无论try块中的语句是失败还是成功,都会执行
无论发生什么,
如果移动
1 | print(foo.read()) |
在您的示例中抛出
无论如何,