A
A
alex_les2021-10-05 16:07:22
Python
alex_les, 2021-10-05 16:07:22

Why is the full exception stack not visible?

I need a function that catches the exception stack. However, it turned out that a simple method like

try:
    raising_func()
except Exception:
    _, _, tb = sys.exc_info()

works only if it is explicitly written, and called from the function like this
#перехватывающая функция
   def stack_capture(func):
       try:
           func()
       except Exception:
           _, _, tb = sys.exc_info()
       return tb

#вызов
def some_function()
    my_tb = stack_capture(raising_func)

returns only the top exception thrown inside stack_capture() itself. Why is this happening and is it possible to get the whole stack?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-10-05
@alex_les

returns only the top exception thrown inside stack_capture() itself. Why is this happening and is it possible to get the whole stack?

It actually returns a Traceback object .
This object contains the fields tb_frame (of type Frame object), tb_lineno (line number in the code), tb_lasti (instruction number in byte code) and tb_next - a link to the next Traceback type object.
If you want to deploy a trace, go through the list:
my_tb = stack_capture(raising_func)
    t = my_tb
    while t:
        print(t.tb_frame, t.tb_lineno, t.tb_lasti)
        t = t.tb_next

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question