首页 > 解决方案 > 尝试,使用 if 和 else 的 except 子句

问题描述

让我们想象一下这段代码:

    try:
        if condition1 and condition2: # some_exception may happen here
            function1()
        elif condition3 and condition4: # some_exception may happen here
            function2()
        else:
            big
            block
            of
            instructions
    except some_exception:
        big
        block
        of
        instructions

正如你所看到的,我重复了大量的指令(两者都是相同的)。有没有办法避免重复,但与将代码放在函数中不同?

某种不同的逻辑或使用 finally 或 else 来尝试?我就是想不通。

提前感谢您帮助我!

标签: pythonpython-3.xif-statementexceptionpython-3.7

解决方案


如果你不喜欢使用函数,那么在两个地方都设置一个变量,然后再检查呢?

像这样的东西:

do_stuff = False
try:
    if condition1 and condition2: # some_exception may happen here
        function1()
    elif condition3 and condition4: # some_exception may happen here
        function2()
    else:
        do_stuff = True
except some_exception:
    do_stuff = True
    ...

if do_stuff:
    big
    block
    of
    instructions

推荐阅读