Python异常处理
我正在开发一个Django网站,遇到了一些麻烦,想找出处理异常的最佳方法。我之前是这样做的:
try:
Some code
except:
log error in my own words, i.e 'Some code' failed to execute
Some other code
这样做可以捕捉到所有的异常,确保我的网站不会出现500错误等问题。但是,由于我知识有限,我看不到具体的异常信息,这让我在调试的时候非常困难。我该如何打印出发生的错误呢?目前我只能把try: catch:注释掉,这样才能看到错误并进行修复。肯定有更好的方法!
提前谢谢你们!
Rich
5 个回答
3
这可能会有所帮助
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
x, y = inst.args
print 'x =', x
print 'y =', y
5
#!/usr/bin/env python
import sys
try:
0 / 0
except Exception, e:
print >> sys.stderr, 'Hello %s' % e
# Hello integer division or modulo by zero
注意,你可以在一个代码块中捕捉多个异常,比如:
try:
open(filename)
except NameError, e:
print >> sys.stderr, e
except IOError, ioe:
print >> sys.stderr, ioe
关于异常处理的更多信息可以在这个教程中找到:
25
你可以把异常信息放到一个异常变量里:
try:
# some code
except Exception, e:
# Log the exception.
有很多种方法可以格式化异常信息,Python的日志模块(我假设你在用Django)可以帮助你格式化异常。而且,异常本身在转换成字符串时通常会显示一些有用的信息。
下面是一个例子:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
1/0
except Exception as e:
logging.exception(e)
这个例子使用了新的“as”语法来捕捉异常,这种语法在Python 2.6及以后的版本中都支持。上面的输出结果是:
DEBUG:root:This message should go to the log file
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
File "untitled-1.py", line 6, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero