Extract traceback info from an exception object

后端 未结 5 1569
忘掉有多难
忘掉有多难 2020-12-02 10:31

Given an Exception object (of unknown origin) is there way to obtain its traceback? I have code like this:

def stuff():
   try:
       .....
       return us         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 11:05

    Since Python 3.0[PEP 3109] the built in class Exception has a __traceback__ attribute which contains a traceback object (with Python 3.2.3):

    >>> try:
    ...     raise Exception()
    ... except Exception as e:
    ...     tb = e.__traceback__
    ...
    >>> tb
    
    

    The problem is that after Googling __traceback__ for a while I found only few articles but none of them describes whether or why you should (not) use __traceback__.

    However, the Python 3 documentation for raise says that:

    A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable.

    So I assume it's meant to be used.

提交回复
热议问题