25

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()

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Mohamed Khamis
  • 7,731
  • 10
  • 38
  • 58
  • 2
    To print the stack trace without causing an exception to be raised, see: http://stackoverflow.com/questions/3925248/print-python-stack-trace-without-exception-being-raised – Eddified Dec 28 '11 at 19:23

3 Answers3

38

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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()
Community
  • 1
  • 1
MrColes
  • 2,453
  • 1
  • 28
  • 38
  • Just a headsup, [print_stack](http://docs.python.org/2/library/traceback.html#traceback.print_stack) merely prints the stack from whatever line of code you're at, while [print_exc() prints the exception's stack trace](http://docs.python.org/2/library/traceback.html#traceback.print_exception). – abelito Nov 11 '13 at 16:04
2

You can also use logging.exception from the logging module. It will print the current exception's stacktrace into the default logger as a message of severity ERROR.

Link: http://docs.python.org/2/library/logging.html#logging.Logger.exception

Milimetric
  • 13,411
  • 4
  • 44
  • 56
Xion
  • 22,400
  • 10
  • 55
  • 79