How to print an exception in Python? How to print an exception in Python? python 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 tracebacktry:    1/0except Exception:    traceback.print_exc()

Output:

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


In Python 2.6 or greater it's a bit cleaner:

except Exception as e: print(e)

In older versions it's still quite readable:

except Exception, e: print e


matomo