pythonpython-3.x

Storing and printing an exception with traceback?


In a python3 program I have a certain try...except block where I store exceptions that occur in a certain method into a list of exceptions that have occurred. A simplified version looks like this:

def the_method(iterable):
   errors = []
   for i in iterable:
       try:
           something(i)
        except Exception as e:
            errors.append(e)
   return errors

After the method returns I want to print the errors in the console. How can I print the exceptions with traceback and the usual uncaught exception formatting?


Solution

  • Use the traceback module. For Python 3.10 and up, you can just write

    for exc in errors:
        traceback.print_exception(exc)
    

    On previous versions, traceback.print_exception only supports the old type/value/traceback format, so you'll have to extract type(exc) and exc.__traceback__ yourself:

    for exc in errors:
        traceback.print_exception(type(exc), exc, exc.__traceback__)
    

    Also, be aware that Python has a very strange way of building tracebacks, where an entry for a stack frame is added to the traceback when an exception propagates into that stack frame, rather than building the traceback all at once when the exception is created or raised.

    This means that an exception's traceback stops at the point where it stopped propagating. When your the_method catches an exception, the exception's traceback will stop at the_method.