Main Content

Reporting the full stack trace when you catch a Python exception

Archive - Originally posted on "The Horse's Mouth" - 2012-11-22 08:36:03 - Graham Ellis

Python exceptions are a safety net which let you catch data or program problems or other unexpected issues without having to explicity code each and every potential problem or problem group - a wonderful fail safe mechanism.

If you fail to write your Python code with try and except blocks, it will use the default (built in) exception handler, which give you a full stack trace (a confession) and exits the program. Thus

  def doit():
    a = 6 /0
  doit()


gives

  wizard:nov12 graham$ python tiny
  Traceback (most recent call last):
    File "tiny", line 3, in
      doit()
    File "tiny", line 2, in doit
      a = 6 /0
  ZeroDivisionError: integer division or modulo by zero
  wizard:nov12 graham$


Within your own exception handlers ...
• you can pick up your exception object and generate your own message.
• you can use the message and __class__.__name__ objects to report Python's own message and class name
• you can use the traceback module to print out a full confession

Here's a code snippet showing you the standard and traceback items in use:
  except Exception,e:
    print e.message
    print e.__class__.__name__
    traceback.print_exc(e)


A full example including traceback use from yesterday's Intermediate Python Course is [here].