添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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 Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-by-zero error below, but how can I print that fact?

x = 0 y = 1 z = y / x z = z + 1 print "z=%d" % (z) except: print "Values at Exception: x=%d y=%d " % (x,y) print "The error was on line ..." print "The reason for the error was ..."

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

import traceback
  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()

Thanks. I was really looking for the "traceback" - couldn't remember what it was called, because I was looking for an error or exception object. – NealWalters Dec 30 '10 at 6:04 The DivideByZero was just a simple error used for my post, my actual situation is much more complex. – NealWalters Dec 30 '10 at 6:10

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

import sys, traceback, logging
logging.basicConfig(level=logging.ERROR)
    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 <module>
    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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required. rev 2019.3.22.33110