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


当前回答

就是这样。try-except子句中的'else'块用于当(且仅当)被试操作成功时运行的代码。它可以被利用,也可以被滥用。

try:
    fp= open("configuration_file", "rb")
except EnvironmentError:
    confdata= '' # it's ok if the file can't be opened
else:
    confdata= fp.read()
    fp.close()

# your code continues here
# working with (possibly empty) confdata

就我个人而言,我喜欢它,并在适当的时候使用它。它在语义上对语句进行分组。

其他回答

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

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记录有用的警告消息。

PEP 380中有一个很好的try-else示例。基本上,它归结为在算法的不同部分做不同的异常处理。

大概是这样的:

try:
    do_init_stuff()
except:
    handle_init_suff_execption()
else:
    try:
        do_middle_stuff()
    except:
        handle_middle_stuff_exception()

这允许您在异常发生的地方编写异常处理代码。

也许它的用法是:

#debug = []

def debuglog(text, obj=None):
    " Simple little logger. "
    try:
        debug   # does global exist?
    except NameError:
        pass    # if not, don't even bother displaying
    except:
        print('Unknown cause. Debug debuglog().')
    else:
        # debug does exist.
        # Now test if you want to log this debug message
        # from caller "obj"
        try:
            if obj in debug:
                print(text)     # stdout
        except TypeError:
            print('The global "debug" flag should be an iterable.')
        except:
            print('Unknown cause. Debug debuglog().')

def myfunc():
    debuglog('Made it to myfunc()', myfunc)

debug = [myfunc,]
myfunc()

也许这对你也有帮助。

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-条件,使其显式。

else块通常可以用来补充出现在每个except块中的功能。

try:
    test_consistency(valuable_data)
except Except1:
    inconsistency_type = 1
except Except2:
    inconsistency_type = 2
except:
    # Something else is wrong
    raise
else:
    inconsistency_type = 0

"""
Process each individual inconsistency down here instead of
inside the except blocks. Use 0 to mean no inconsistency.
"""

在这种情况下,在每个except块中设置inconsistency_type,以便在无错误情况下在else中补充行为。

当然,我将此描述为某一天可能会出现在您自己的代码中的模式。在这个特定的情况下,您只要在try块之前将inconsistency_type设置为0即可。