How to print an exception in Python?


Question

try:
    something here
except:
    print 'the whatever error occurred.'

How can I print the error/exception in my except: block?

1
552
12/19/2018 7:51:27 PM

Accepted Answer

For Python 2.6 and later and Python 3.x:

except Exception as e: print(e)

For Python 2.5 and earlier, use:

except Exception,e: print str(e)
823
8/16/2018 8:01:37 AM

The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

Output:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon