Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java's printStackTrace() equivalent in python [duplicate]

Tags:

In python except block, I want to print the error message but I don't want the program to stop executing, I understand that I have to do something like this

try:     1/0 except:      print errorMessage 

In the except part, I am looking to put something like java's printStackTrace()

like image 577
Mohamed Khamis Avatar asked Oct 26 '11 10:10

Mohamed Khamis


People also ask

What can I use instead of E printStackTrace?

Loggers should be used instead of printing the whole stack trace on stream. e. printStackTrace() prints a Throwable and its stack trace to stream which could inadvertently expose sensitive information. Loggers should be used instead to print Throwables, as they have many advantages.

Why we should not use e printStackTrace ()?

e. printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes. The better thing to do is to use a logging framework (logback, slf4j, java.

What is the use of e printStackTrace () in catch block?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.

How do I print a stack trace error in Python?

if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller's frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed. If the file argument is None, the output goes to sys.


2 Answers

Take a look at traceback.print_exc() and the rest of the traceback module.

import traceback  try:     1/0 except:     print '>>> traceback <<<'     traceback.print_exc()     print '>>> end of traceback <<<' 

There are some more examples towards the end of the traceback documentation page.

like image 117
NPE Avatar answered Nov 09 '22 13:11

NPE


If you really just want the error message, you can just print the error (notice how I specify the exception in the except—that’s good practice, see pep8 for recommendations on catching errors):

try:     1/0 except Exception as e:     print e 

However, if you want the stackstrace, as @Eddified said in a comment, you can use the example in this answer. Or more specifically for your case:

import traceback try:     1/0 except Exception as e:     print e     traceback.print_stack() 
like image 38
MrColes Avatar answered Nov 09 '22 12:11

MrColes