尝试,带if的else子句除外

时间:2019-03-14 19:17:40

标签: python python-3.x if-statement exception python-3.7

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

    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

如您所见,我重复了大量的说明(两者相同)。 有没有办法避免重复,但是与将代码放入函数中有所不同吗?

某种不同的逻辑还是使用final还是尝试?我只是想不通。

预先感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

如果您不喜欢使用函数,那么如何在两个位置都设置一个变量,然后再进行检查?

类似这样的东西:

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

答案 1 :(得分:1)

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的建议改为加薪