处理特定的和一般的Python异常?

时间:2013-07-25 14:28:39

标签: python

我想捕获一个特定的异常并相应地处理它 - 然后我想继续并执行其他异常所必需的泛型处理。

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

这就是我目前正在做的事情,它运作良好:

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

Tldr:

即 - 有“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子句 - 这不是用于整理(即关闭文件)·

2 个答案:

答案 0 :(得分:10)

您可以重新加载异常,并在嵌套设置的外部处理程序中处理通用案例:

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

答案 1 :(得分:4)

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命令导致 捕获异常以传递到外部块。