Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch and print the full exception traceback without halting/exiting the program?

I want to catch and log exceptions without exiting, e.g.,

try:     do_stuff() except Exception as err:     print(Exception, err)     # I want to print the entire traceback here,     # not just the exception name and details 

I want to print the exact same output that is printed when the exception is raised without the try..except intercepting the exception, and I do not want it to exit my program. How do I do this?

like image 435
chriscauley Avatar asked Sep 13 '10 17:09

chriscauley


People also ask

How do you print an exception in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How do I print an exception stack trace?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.


1 Answers

traceback.format_exc() or sys.exc_info() will yield more info if that's what you want.

import traceback import sys  try:     do_stuff() except Exception:     print(traceback.format_exc())     # or     print(sys.exc_info()[2]) 
like image 88
volting Avatar answered Sep 22 '22 20:09

volting