我们常常想在没有触发异常的时候执⾏⼀些代码,这可以很轻松地通过⼀个else从句来达到。
有⼈也许问了:如果你只是想让⼀些代码在没有触发异常的情况下执⾏,为啥你不直接把代码放在try⾥⾯呢?
回答是,那样的话这段代码中的任意异常都还是会被try捕获,⽽你并不⼀定想要那样。
⼤多数⼈并不使⽤else从句,⽽且坦率地讲我⾃⼰也没有⼤范围使⽤。
这⾥是个例⼦:
try:
print('I am sure no exception is going to occur!')
except Exception:
print('exception')
else:
# 这⾥的代码只会在try语句⾥没有触发异常时运⾏,
# 但是这⾥的异常将 *不会* 被捕获
print('This would only run if no exception occurs. And an error here ' 'would NOT be caught.')
finally:
print('This would be printed in every case.')
输出:
I am sure no exception is going to occur!
This would only run if no exception occurs. And an error here would NOT be
caught.
This would be printed in every case.
本文探讨了在Python中如何使用else从句在不捕获异常的情况下执行特定代码,与直接将代码置于try内的区别,并通过实例说明了else在控制流程中的作用。
1612

被折叠的 条评论
为什么被折叠?



