How to print an exception in Python?

How to print an exception in Python?

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)

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:scriptsdivide_by_zero.py, line 4, in <module>
    1/0
ZeroDivisionError: division by zero

How to print an exception in Python?

In Python 2.6 or greater its a bit cleaner:

except Exception as e: print(e)

In older versions its still quite readable:

except Exception, e: print e

Leave a Reply

Your email address will not be published. Required fields are marked *