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コマンドにより、キャッチされた例外が外側のブロックに渡されます。tryexcept

于 2013-07-25T14:32:53.403 に答える