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

前端 未结 7 802
萌比男神i
萌比男神i 2020-12-24 05:51

I\'m not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has E

7条回答
  •  天涯浪人
    2020-12-24 06:41

    A better approach is to make use of the standard Python Logging module.

    import sys, traceback, logging
    
    logging.basicConfig(level=logging.ERROR)
    
    try: 
        x = 0 
        y = 1 
        z = y / x 
        z = z + 1 
        print "z=%d" % (z) 
    except: 
        logging.exception("Values at Exception: x=%d y=%d " % (x,y))
    

    This produces the following output:

    ERROR:root:Values at Exception: x=0 y=1 
    Traceback (most recent call last):
      File "py_exceptions.py", line 8, in 
        z = y / x
    ZeroDivisionError: integer division or modulo by zero
    

    The advantage of using the logging module is that you have access to all the fancy log handlers (syslog, email, rotating file log), which is handy if you want your exception to be logged to multiple destinations.

提交回复
热议问题