Python try/except: Showing the cause of the error after displaying my variables

If you're expecting a DivideByZero error, you can catch that particular error

import traceback
try:
  x = 5
  y = 0
  print x/y
except ZeroDivisionError:
  print "Error Dividing %d/%d" % (x,y)
  traceback.print_exc()
except:
  print "A non-ZeroDivisionError occurred"

You can manually get the line number and other information by calling traceback.print_exc()


The string value of the exception object will give you the reason. The traceback module will allow you access to the full traceback.


try:  
    1 / 0 
except Exception as e: 
    print(e)