tryexcept块:如果引发异常,则模拟“else”

2024-10-01 07:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的代码:

try:
    return make_success_result()
except FirstException:
    handle_first_exception()
    return make_error_result()
except SecondException:
    handle_second_exception()
    return make_error_result()

我想知道有什么办法可以做到:

^{pr2}$

因此,代码按以下顺序之一执行:

try > else > finally
try > except > ???? > finally

EDIT: my point here is that ???? block should execute right after ANY of the except blocks, meaning that it's an addition to error handling, not a substitution.


Tags: 代码makereturnthatexceptionerrorresultfirst
3条回答

您可以:

try:
    # Do something
except Error1:
    # Do Error1 specific handling
except Error2:
    # Do Error2 specific handling
except Exception:
    # Handle any other exception (Generic exception handling)
else:
    # Do this if there were no exceptions
finally:
    # Execute this regardless

在这种情况下,我要做的是在出现异常时设置一个布尔值,如下所示:

got_exception = False
try:
    # do something
except Error1:
    # do Error1 specific handling
    got_exception = True
except Error2:
    # do Error2 specific handling
    got_exception = True
else:
    # If there was no exception
finally:
    if got_exception:
        # ALSO do this if there was ANY exception (e.g. some common error handling)

这应该符合您的需要,这是IMO将所有解决方案组合成最易读的代码结构的最干净的方法,这将是最容易调试的。在

你可以这样做:

try:
    print 'try'
    # 1/0
    # {}[1]
    # {}.a
except AttributeError, KeyError:  # only handle these exceptions..
    try:
        raise                     # re-raise the exception so we can add a finally-clause executing iff there was an exception.
    except AttributeError:
        print 'attrerr'
        # raise ...               # any raises here will also execute 'common'
    except KeyError:
        print 'keyerror'
    finally:                      # update 0: you wanted the common code after the exceptions..
        print "common"

else:
    print 'no exception'

但这是可怕的,我不会建议你没有大量的评论来说明为什么。。在

更新:除了内部try块中有趣的异常之外,您不需要捕获任何内容。代码已更新。在

UPDATE2:根据操作说明,common应该在引发有趣的异常时执行。代码已更新。@马特泰勒的版本绝对是最好的选择;-)

相关问题 更多 >