LoginSignup
6
4

More than 5 years have passed since last update.

Pythonの例外型やスタックトレースを確認する

Posted at

概要

sysモジュールの exc_info メソッドを使うと、例外オブジェクトやスタックトレースオブジェクトのインスタンスを受け取ることができる

サンプルコード

import sys
import traceback

try:
    1/0
except Exception:
    a, b, c = sys.exc_info()  # type, value, traceback
    print('=========================================================')
    print(type(a))
    print(a)
    print('=========================================================')
    print(type(b))
    print(b)
    print('=========================================================')
    print(type(c))
    print(c)
    print('=========================================================')
    traceback.print_tb(c)
    print('=========================================================')

実行結果

=========================================================
<class 'type'>
<class 'ZeroDivisionError'>
=========================================================
<class 'ZeroDivisionError'>
division by zero
=========================================================
<class 'traceback'>
<traceback object at 0x1099f60c8>
=========================================================
  File "test.py", line 5, in <module>
    1/0
=========================================================
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4