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

Old*_*oil 5 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 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
Run Code Online (Sandbox Code Playgroud)

非限定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
Run Code Online (Sandbox Code Playgroud)


lar*_*sks 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
Run Code Online (Sandbox Code Playgroud)

但听起来您希望最后一个子句既适用于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
Run Code Online (Sandbox Code Playgroud)

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