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()
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.
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With