Python 的通用捕获

我有一些非常奇怪的行为,似乎导致无声的异常。如何编写一个通用的 try catch 来调试所有异常。类似于:

try:
# something that fails
except e:
print e

更多关于手头问题的细节:

我有一个 Django 应用程序,在我的电脑上(Ubuntu Linux 8.10)通过 runserver 和 mod-python 都可以很好地工作。在部署服务器(Ubuntu Linux 8.10)上,它通过 runserver 工作得很好,但是通过 mod-python 中的 apache 失败。

我已经将原因简化为使用 Berkeley DB (bsddb.DB)和辅助键的应用程序的一部分。辅助键的回调方法使用 pickle 格式化键。当我对单个值调用 pickle 时,它会失败。但是,只有在使用 cPickle 时才会失败,并且在回调函数之外的相同值上使用 pickle 也是可行的。

我只是想知道为什么泡菜会失败。

102036 次浏览

Does this work? :

except BaseException, e:

The traceback module is quite useful for formatting tracebacks. You can then write it to a logfile.

Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this:

try:
something()
except Exception as e:
send_somewhere(traceback.format_exception(*sys.exc_info()))
raise # reraises the exception

note that this format using the as keyword is for python > 2.6. The old way was:

except Exception, e: