6

我想捕获一个特定的异常并相应地处理它——然后我想继续并执行其他异常必须执行的通用处理。

来自 C 背景,我以前可以使用 goto 来达到预期的效果。

这就是我目前正在做的事情,它工作正常:

try:
    output_var = some_magical_function()
except IntegrityError as zde:
    integrity_error_handling()
    shared_exception_handling_function(zde) # could be error reporting
except SomeOtherException as soe:
    shared_exception_handling_function(soe) # the same function as above

语言:

即 - 是否有执行以下操作的“Pythonic”方式:

try:
    output_var = some_magical_function()
except IntegrityError as zde:
    integrity_error_handling()
except ALLExceptions as ae: # all exceptions INCLUDING the IntregityError
    shared_exception_handling_function(ae) # could be error reporting

注意:我知道 finally 子句 - 这不是为了整理(即关闭文件)·

4

2 回答 2

11

您可以重新引发异常,并在嵌套设置的外部处理程序中处理一般情况:

try:
    try:
        output_var = some_magical_function()
    except IntegrityError as zde:
        integrity_error_handling()
        raise
except ALLExceptions as ae: # all exceptions INCLUDING the IntregityError
    shared_exception_handling_function(ae) # could be error reporting

不合格raise语句重新引发当前异常,因此IntegrityError再次抛出异常以由AllExceptions处理程序处理。

您可以采取的另一条路径是测试异常类型:

try:
    output_var = some_magical_function()
except ALLExceptions as ae: # all exceptions INCLUDING the IntregityError
    if isinstance(ae, IntegrityError):
        integrity_error_handling()
    shared_exception_handling_function(ae) # could be error reporting
于 2013-07-25T14:32:46.280 回答
5

该类Exception将匹配所有异常...

try:
    output_var = some_magical_function()
except IntegrityError as zde:
    integrity_error_handling()
except Exception as ae:
    shared_exception_handling_function(ae) # could be error reporting

但听起来您希望最后一个子句同时适用于IntegrityError例外以及其他所有情况。所以你需要一个不同的结构,可能是这样的:

try:
    try:
        output_var = some_magical_function()
    except IntegrityError as zde:
        integrity_error_handling()
        raise
except Exception as ae:
    shared_exception_handling_function(ae) # could be error reporting

raise内部try...块上的命令except导致捕获的异常被传递到外部块。

于 2013-07-25T14:32:53.403 回答