try语句的可选else子句的预期用途是什么?


当前回答

else:块令人困惑并且(几乎)毫无用处。它也是for和while语句的一部分。

实际上,即使在if语句中,else:也可能被滥用,造成非常难以发现的错误。

考虑这一点。

   if a < 10:
       # condition stated explicitly
   elif a > 10 and b < 10:
       # condition confusing but at least explicit
   else:
       # Exactly what is true here?
       # Can be hard to reason out what condition is true

三思而后行。这通常是个问题。除非在if语句中,否则避免使用它,即使在if语句中,也要考虑记录else-条件,使其显式。

其他回答

即使你现在想不出它的用途,你可以打赌它一定会有用处的。下面是一个没有想象力的例子:

其他:

a = [1,2,3]
try:
    something = a[2]
except IndexError:
    print("out of bounds")
else:
    print(something)

没有其他的:

try:
    something = a[2]
except IndexError:
    print("out of bounds")

if "something" in locals():
    print(something)

在这里,如果没有抛出错误,则定义了变量something。您可以在try块之外删除它,但如果定义了变量,则需要进行一些混乱的检测。

else:块令人困惑并且(几乎)毫无用处。它也是for和while语句的一部分。

实际上,即使在if语句中,else:也可能被滥用,造成非常难以发现的错误。

考虑这一点。

   if a < 10:
       # condition stated explicitly
   elif a > 10 and b < 10:
       # condition confusing but at least explicit
   else:
       # Exactly what is true here?
       # Can be hard to reason out what condition is true

三思而后行。这通常是个问题。除非在if语句中,否则避免使用它,即使在if语句中,也要考虑记录else-条件,使其显式。

我发现其他有用的处理可能不正确的配置文件:

try:
    value, unit = cfg['lock'].split()
except ValueError:
    msg = 'lock monitoring config must consist of two words separated by white space'
    self.log('warn', msg)
else:
     # get on with lock monitoring if config is ok

读取锁配置的异常禁用锁监控,ValueErrors记录有用的警告消息。

使用else样式和可读性是一个重要原因。将可能导致异常的代码放在处理异常的代码附近通常是个好主意。例如,比较这些:

try:
    from EasyDialogs import AskPassword
    # 20 other lines
    getpass = AskPassword
except ImportError:
    getpass = default_getpass

and

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
else:
    # 20 other lines
    getpass = AskPassword

当异常不能提前返回或重新抛出异常时,第二个方法很好。如果可能的话,我会这样写:

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
    return False  # or throw Exception('something more descriptive')

# 20 other lines
getpass = AskPassword

注意:答案从最近发布的副本复制在这里,因此所有这些“AskPassword”的东西。

查看Python引用,当没有异常时,else似乎在try之后执行。 当控制流出try子句的末尾时,执行可选的else子句。else子句中的异常不由前面的except子句处理。

Dive into python有一个例子,如果我理解正确的话,在try块中他们尝试导入一个模块,当失败时,你会得到异常并绑定默认值,但当它工作时,你可以选择进入else块并绑定所需的内容(参见示例和解释链接)。

如果你试图在catch块中工作,它可能会抛出另一个异常——我想这就是else块派上用场的地方。