简体   繁体   English

try-except 块:如果引发异常,则类似于“else”

[英]try-except block: analogue for 'else' if exception was raised

I have this kind of code:我有这样的代码:

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

And I'm wondering is there any way I can achieve this:我想知道有什么办法可以做到这一点:

try:
    # do something
except Error1:
    # do Error1 specific handling
except Error2:
    # do Error2 specific handling
else:
    # do this if there was no exception
????:
    # ALSO do this if there was ANY of the listed exceptions (e.g. some common error handling)

So the code is executed in one of following sequences:因此,代码按以下序列之一执行:

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.块应该在任何一个except块之后立即执行,这意味着它是对错误处理的补充,而不是替代。

What I would do in that case is to set a boolean when you get an exception, like so: 在这种情况下我要做的是在你得到异常时设置一个布尔值,如下所示:

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)

This should fit your needs, which is IMO the cleanest way of combining all of the solutions which have been presented into the most readable code structure that's going to be the easiest to debug. 这应该符合您的需求,这是IMO最简单的方法,将所有已呈现的解决方案组合到最易于调试的最易读的代码结构中。

You can do: 你可以做:

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

You can actually do this: 你实际上可以这样做:

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'

but it is horrid and I would not suggest that you do without copious amounts of comments describing why.. 但它是可怕的,我不建议你没有大量的评论描述为什么..

UPDATE: you don't need to catch anything but the interesting exceptions in the inner try-block. 更新:除了内部try-block中的有趣异常之外,您不需要捕获任何内容。 Code updated. 代码已更新。

UPDATE2: per OP's clarification, common should just be executed when an interesting exception is thrown. UPDATE2:根据OP的说明,当抛出一个有趣的异常时,应该执行common Code updated. 代码已更新。 @MattTaylor's version is definitely the way to go ;-) @MatTaylor的版本绝对是要走的路;-)

Yes, exception handling in python includes both an else and a finally clause. 是的,python中的异常处理包括elsefinally子句。 You can do this: 你可以这样做:

try:
    # do something
except Error1:
    # do Error1 specific handling
except Error2:
    # do Error2 specific handling
else:
    # do this if there was no exception
finally:
    # Do this in any case!

The python docs mention these blocks, even though it doesn't show the full example you need. python文档提到了这些块,即使它没有显示您需要的完整示例。


EDIT: I see that you do not ask specifically for the clean-up in the general case. 编辑:我看到你没有专门要求清理一般情况。 Python docs put it this way: Python文档就是这样说的:

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. try语句有另一个可选子句,用于定义必须在所有情况下执行的清理操作。

Note that the finally will run whether there was an exception or not. 请注意, finally将运行是否存在异常。 Combined with the else block, you should still be able to do what you want. 结合else块,你仍然可以做你想要的。

You could trap all errors and check for its type in the error handling code like this: 您可以捕获所有错误并在错误处理代码中检查其类型,如下所示:

try:
    # do something
except Exception as e:
    if isinstance(e, Error1):
        # do Error1 specific handling
    elif isinstance(e, Error2):
        # do Error2 specific handling
    else:
        # do non-Error1/Error2 handling
    # ALSO do this if there was ANY exception (e.g. some common error handling)
else:
    # do this if there was no exception

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM