Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
OdraEncoded Avatar asked Sep 06 '13 17:09

OdraEncoded


1 Answers

Use the traceback module. Note that the interface is ancient, so it doesn't know to use type(exc) and exc.__traceback__; you'll have to extract those yourself:

for exc in errors:
    traceback.print_exception(type(exc), exc, exc.__traceback__)
like image 175
user2357112 supports Monica Avatar answered Oct 13 '22 12:10

user2357112 supports Monica