'Python 异常处理'

2024-04-25 00:03:07 发布

您现在位置: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:并查看错误并修复它。一定有更好的办法!

提前谢谢

富有的


Tags: django方法inlog站点my错误code
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

在异常变量中捕获异常:

try:
    # some code
except Exception, e:
    # Log the exception.

格式化异常有多种方法,日志模块(我假设您/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”语法来捕获异常,这在Python2.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
#!/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

有关异常处理的更多信息,请参见本教程:

相关问题 更多 >