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


当前回答

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()

也许这对你也有帮助。

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

例子:

try:
    age=int(input('Enter your age: '))
except:
    print ('You have entered an invalid value.')
else:
    if age <= 21:
        print('You are not allowed to enter, you are too young.')
    else:
        print('Welcome, you are old enough.')

输出:

>>> 
Enter your age: a
You have entered an invalid value.
>>> RESTART
>>> 
Enter your age: 25
Welcome, you are old enough.
>>> RESTART
>>> 
Enter your age: 13
You are not allowed to enter, you are too young.
>>> 

复制自:https://geek-university.com/python/the-try-except-else-statements/

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即可。

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

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

如果你试图在catch块中工作,它可能会抛出另一个异常——我想这就是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

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