Coder Perfect

In Python, how do you print an exception?


    something here
    print('the whatever error occurred.')

In my except: block, how can I publish the error/exception?

Asked by TIMEX

Solution #1

Python 2.6 and beyond, as well as Python 3.x:

except Exception as e: print(e)

Use: for Python 2.5 and before.

except Exception,e: print str(e)

Answered by jldupont

Solution #2

The traceback module has methods for formatting and printing exceptions and their tracebacks, such as this, which prints the exception in the same way as the default handler:

import traceback

except Exception:


Traceback (most recent call last):
  File "C:\scripts\", line 4, in <module>
ZeroDivisionError: division by zero

Answered by Cat Plus Plus

Solution #3

It’s a little cleaner in Python 2.6 or later:

except Exception as e: print(e)

It’s still readable in older versions:

except Exception, e: print e

Answered by ilya n.

Solution #4

Here’s an example from Errors and Exceptions if you want to pass error strings (Python 2.6)

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

Answered by Nick Dandoulakis

Solution #5

(I was going to remark on @jldupont’s response, but I don’t have enough reputation.)

I’ve seen answers similar to @jldupont’s answer elsewhere as well. To be clear, I believe it is critical to mention that:

except Exception as e:

By default, the error output is written to sys.stdout. In general, a more acceptable method to error handling would be:

except Exception as e:
    print(e, file=sys.stderr)

(Importing sys is required for this to operate.) This route reports the error to STDERR rather than STDOUT, allowing for correct output parsing/redirection/etc. I appreciate that the question was only about ‘publishing an error,’ but it seems vital to mention the proper practice here rather than omitting this detail, which could lead to non-standard code for those who don’t learn better.

I haven’t utilized the traceback module like Cat Plus Plus suggested, and perhaps it is the best option, but I thought I’d mention it.

Answered by grish

Post is based on