except: と except Exception as e: の違い 質問する

except: と except Exception as e: の違い 質問する

except:次のコードスニペットは両方とも同じことを行います。すべての例外をキャッチし、ブロック内のコードを実行します。

スニペット 1 -

try:
    #some code that may throw an exception
except:
    #exception handling code

スニペット2 -

try:
    #some code that may throw an exception
except Exception as e:
    #exception handling code

両方の構造の違いは正確には何でしょうか?

ベストアンサー1

2 番目では、例外オブジェクトの属性にアクセスできます。

>>> def catch():
...     try:
...         asd()
...     except Exception as e:
...         print e.message, e.args
... 
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)

しかし、BaseExceptionシステム終了例外はキャッチされませんSystemExitKeyboardInterruptGeneratorExit

>>> def catch():
...     try:
...         raise BaseException()
...     except Exception as e:
...         print e.message, e.args
... 
>>> catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch
BaseException

ベア except は次のことを行います:

>>> def catch():
...     try:
...         raise BaseException()
...     except:
...         pass
... 
>>> catch()
>>> 

詳細については、ドキュメントの組み込み例外セクションとチュートリアルのエラーと例外セクションを参照してください。

おすすめ記事