私たちは次のようなものを除いて内側の試みを持っています
try:
try: (problem here)
except: (goes here)
except: (will it go here) ??
それを除いて、試行の正しい流れですか?外部のtryブロックの内部で例外がキャッチされた場合、そのエラーまたは非エラー?
いいえ、最初の例外が発生しない限り、2番目の問題は発生しません。
条項に入るexcept
と、例外を再度発生させない限り、「例外がキャッチされました。処理します」とほとんど言っています。たとえば、この構成は非常に便利な場合があります。
try:
some_code()
try:
some_more_code()
except Exception as exc:
fix_some_stuff()
raise exc
except Exception as exc:
fix_more_stuff()
これにより、同じ例外に対して多くの「修正」レイヤーを作成できます。
except
次のように、その内部で別の例外を発生させない限り、外部には到達しません。
try:
try:
[][1]
except IndexError:
raise AttributeError
except AttributeError:
print("Success! Ish")
内側のexcept
ブロックが外側のブロックに例外フィッティングを発生させない限り、エラーとしてカウントされません。
エラーは外側にヒットしませんExcept
。あなたはそのようにそれをテストすることができます:
x = 'my test'
try:
try: x = int(x)
except ValueError: print 'hit error in inner block'
except: print 'hit error in outer block'
これは印刷するだけ'hit error in inner block'
です。
ただし、inner Try
/Except
ブロックの後に他のコードがあるとすると、エラーが発生します。
x, y = 'my test', 0
try:
try: x = int(x)
except ValueError: print 'x is not int'
z = 10./y
except ZeroDivisionError: print 'cannot divide by zero'
'x is not int'
これにより、 ANDの両方が出力されます'cannot divide by zero'
。