私は次のことができると知っています:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
これもできます:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
しかし、2 つの異なる例外内で同じことを実行したい場合、現時点で考えられる最善の方法は次のようになります。
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
次のようなことを実行する方法はありますか (両方の例外で実行するアクションは であるためsay please
):
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
これは次の構文と一致するため、実際には機能しません。
try:
# do something that may fail
except Exception, e:
# say please
したがって、2 つの異なる例外をキャッチしようとする私の努力は、正確にはうまくいきません。
これを実行する方法はありますか?
ベストアンサー1
except節では、括弧で囲まれたタプルとして複数の例外を指定することができます。たとえば、
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
または、Python 2 の場合のみ:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
例外と変数をカンマで区切ることは Python 2.6 および 2.7 では引き続き機能しますが、これは現在非推奨であり、Python 3 では機能しません。現在は を使用する必要がありますas
。