0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python の traceback で例外発生時の情報を取得

Posted at

Python の traceback で例外発生時の情報を取得する方法のメモ。

プログラム

以下で traceback で取得できる情報を確認する。

traceback.py
import traceback


def func():
    print(f"func(): begin")
    raise "error"
    print(f"func(): end")


def main():
    print(f"main(): start")
    try:
        func()
    except Exception as e:
        print("\ntraceback.format_exception()")
        print(traceback.format_exception(e))

        print("\ntraceback.format_stack()")
        print(traceback.format_stack())

        print("\ntraceback.extract_tb(e.__traceback__)")
        print(traceback.extract_tb(e.__traceback__))

        print("\ne.__traceback__")
        print(e.__traceback__)

    print(f"main(): end")
    return 0


if __name__ == "__main__":
    res = main()
    exit(res)

実行結果

traceback.format_exception()

['Traceback (most recent call last):\n', '  File "/.../traceback.py", line 18, in main\n    func()\n', '  File "/.../traceback.py", line 11, in func\n    raise "error"\n', 'TypeError: exceptions must derive from BaseException\n']

traceback.format_stack()

python:
['  File "/.../traceback.py", line 37, in <module>\n    res = main()\n', '  File "/.../traceback.py", line 24, in main\n    print(traceback.format_stack())\n']

traceback.extract_tb(e.traceback)

['  File "/.../traceback.py", line 37, in <module>\n    res = main()\n', '  File "/.../traceback.py", line 24, in main\n    print(traceback.format_stack())\n']

e.traceback

<traceback object at 0x7fbf1770b740>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?