2016-11-20 3 views
1

Pythonでtry/catchブロック内で処理を続ける方法があるかどうか不思議です、例外をキャッチしてそのプロパティを見て、関連していない場合はスタックを続けます。python:例外フロー:キャッチ後にキャッチブロックを続けますか?

try: 
    # Code 
except AppleError as apple_ex: 
    # look at 'apple_ex.error_code' error body, and if not relevant, 
    # continue on to next down the catch block... 
    # In other words, proceed to except BananaError and so on down. 
except BananaError as banana_ex: 
    # ... 
except Exception as ex: 
    # ... 

答えて

1

AppleErrorは、errorEcodeが関係ない場合でも、AppleErrorであり、BananaErrorではないため、BananaErrorに落ちる意味がありません。あなたが代わりに別のエラーコードの特定のエラーを定義することができ

:あなたは、異なる種類を区別するために気にしない場合は

try: raise MacintoshError() 
except MacintoshError as exc: print("mac") 
except GrannySmithError as exc: print("granny smith") 

GRANNY_SMITH_ERROR = 1 
MACINTOSH_ERROR = 2 
class AppleError(Exception): 
    def __init__(self, error_code, *args): 
     super(AppleError, self).__init__(*args) 
     self.error_code = error_code 

class GrannySmithError(AppleError): 
    def __init__(self, *args): 
     super(GrannySmithError, self).__init__(GRANNY_SMITH_ERROR, *args) 

class MacintoshError(AppleError): 
    def __init__(self, *args): 
     super(MacintoshError, self).__init__(MACINTOSH_ERROR, *args) 

次に、あなたが特定のエラーに一致するように試みることができますアップルのエラーのすべてをトラップすることができます:

try: raise MacintoshError() 
except AppleError as exc: print("generic apple") 

ヨuがないMacintosh用、唯一のグラニースミスのための特別な処理をして、例えば、これらを組み合わせることができます。

try: raise MacintoshError() 
except GrannySmithError as exc: print("granny smith") 
except AppleError as exc: print("generic apple") 

重要なことは、最も特定的なものからのエラーを一覧にすることです。 GrannySmithErrorの前にAppleErrorをテストすると、GrannySmithブロックに入ることはありません。

2

これは、Pythonでの例外の処理方法ではありません。 tryブロック内で例外を発生させた場合、exceptにキャッチするとそのブロック内に入りますが、同じレベルの次のexceptには続きません。我々はそれをキャッチし、

try: 
    raise AttributeError() 
except AttributeError: 
    raise TypeError() 
except TypeError: 
    print("it got caught") # will not catch the TypeError raised above 

だから、あなたのtryに、我々はAttributeErrorを上げ、その後、AttributeErrorを引くの内側TypeErrorを上げる:この機能例を観察します。

except TypeErrorますないキャッチTypeErrorいます。

どのように問題を説明しているかに基づいて、例外の処理方法を再考し、エラーの処理を他の場所で判断できるかどうかを確認し、エラーに発生させる必要があります。例えば

def some_func(): 
    try: 
     thing() 
    except SomeException: 
     # analyze the exception here and raise the error you *should* raise 
     if apple_error_thing: 
      raise AppleError 
     elif banana_error_thing: 
      raise BananaError 
     else: 
      raise UnknownException 


def your_func(): 
    try: 
     some_func() 
    except AppleError as e: 
     print('Apple') 
    except BananaError as e: 
     print('Banana') 
    except UnknownException as e: 
     print('Unknown') 
1

いいえ、それは不可能です。にあるかもしれない短いあなたの唯一の解決策では

When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

try文でthe docsから

:例外は、内側exceptによって処理された後、それは外exceptで扱わ取得する能力を持っていません外側のレベルで別のハンドラを持っており、内側のハンドラ内でraise例外を再、それは次のようになります。

try: 
    try: 
     raise ZeroDivisionError 
    except ZeroDivisionError as e: 
     print("caught") 
     raise ZeroDivisionError 
except ZeroDivisionError as f: 
    print("caught") 

今、ネストされたexcept RAIS結果的に同様のハンドラによって捕捉される例外を含む。

関連する問題