Why use else in try/except construct in Python?
我正在学习Python并偶然发现了一个我不能轻易消化的概念:
根据文件:
The try ... except statement has an optional else clause, which, when
present, must follow all except clauses. It is useful for code that
must be executed if the try clause does not raise an exception.
我感到困惑的是,如果try子句没有在try构造中引发异常,为什么必须执行代码 - 为什么不简单地让它遵循try / except在相同的缩进级别? 我认为这将简化异常处理的选项。 或者另一种询问方式是
这个问题有点类似于这个,但我找不到我想要的东西。
仅当
当您有一个可能出错的简短设置或验证部分时,这通常很有用,然后是您使用您设置的资源的块,其中您不想隐藏错误。 您不能将代码放在
一个用例可以是阻止用户定义一个标志变量来检查是否引发了任何异常(正如我们在
一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | lis = range(100) ind = 50 try: lis[ind] except: pass else: #Run this statement only if the exception was not raised print"The index was okay:",ind ind = 101 try: lis[ind] except: pass print"The index was okay:",ind # this gets executes regardless of the exception # This one is similar to the first example, but a `flag` variable # is required to check whether the exception was raised or not. ind = 10 try: print lis[ind] flag = True except: pass if flag: print"The index was okay:",ind |
输出:
1 2 3 | The index was okay: 50 The index was okay: 101 The index was okay: 10 |