【问题标题】:Try, except clause with if, else尝试,使用 if 和 else 的 except 子句
【发布时间】:2019-08-05 19:32:40
【问题描述】:

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

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

提前感谢您帮助我!

【问题讨论】:

  • 您可以在elseexcept 子句中设置一个变量,在块之后,如果设置了变量,请调用您的big block of instructions
  • 从那个大块创建一个函数并在必要的地方调用它。
  • 您可以在else 子句中手动抛出异常,只需将big block 放在except

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


【解决方案1】:

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

类似这样的:

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

【讨论】:

    【解决方案2】:
    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 的建议改为加注

    【讨论】:

      猜你喜欢
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多