Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for Exceptions: How to display which function caused the exception?

$
0
0

Here's a generic way to do which uses the traceback.extract_tb() function to get a list of “pre-processed” stack trace entries which have a subset of what's in a TracebackException object in them from the most recent exception (this is the same information that's in tracebacks when they're display. The last entry contains information about the last function called (i.e. the most recent one) including its name.

import tracebackdef a():    passdef b():    raise RuntimeError('Oops!')def c():    passx = 2try:    if x == 1:        a()    if x == 2:        b()    if x == 3:        c()except Exception as exc:    filename, lineno, funcname, text = traceback.extract_tb(exc.__traceback__)[-1]    raise Exception(f"Problem in function {funcname}()") from exc

Here the output it displays:

Traceback (most recent call last):  File "display-which-function-caused-the-exception.py", line 22, in <module>    b()  File "display-which-function-caused-the-exception.py", line 10, in b    raise RuntimeError('Oops!')RuntimeError: Oops!The above exception was the direct cause of the following exception:Traceback (most recent call last):  File "display-which-function-caused-the-exception.py", line 27, in <module>    raise Exception(f"Problem in function {funcname}()") from excException: Problem in function b()

Viewing all articles
Browse latest Browse all 44

Latest Images

Trending Articles



Latest Images