Try, except 子句 with if, else

Try, except clause with if, else

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

    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 来尝试?我就是想不通。

在此先感谢您对我的帮助!

如果您不喜欢使用函数,在两个地方都设置一个变量,稍后再检查如何?

像这样:

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
try:
    if condition1 and condition2: # some_exception may happen here
        function1()
    elif condition3 and condition4: # some_exception may happen here
        function2()
    else:
         raise some_exception('This is the exception you expect to handle')
except some_exception:
    big
    block
    of
    instructions

这个呢?

根据 kaelwood 的建议更改为加注