Python:如何以另一种方式处理任何未处理的异常?

时间:2009-08-05 19:46:06

标签: python exception

通常未处理的异常会转到stdout(或stderr?),我正在构建一个应用程序,我想在关闭之前将此信息传递给GUI并将其显示给用户,同时我想写它到一个日志文件。所以,我需要一个带有异常全文的str。

我该怎么做?

4 个答案:

答案 0 :(得分:16)

使用sys.excepthook替换基本异常处理程序。你可以这样做:

import sys
from PyQt4 import QtGui

import os.path
import traceback

def handle_exception(exc_type, exc_value, exc_traceback):
  """ handle all exceptions """

  ## KeyboardInterrupt is a special case.
  ## We don't raise the error dialog when it occurs.
  if issubclass(exc_type, KeyboardInterrupt):
    if QtGui.qApp:
      QtGui.qApp.quit()
    return

  filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  filename = os.path.basename( filename )
  error    = "%s: %s" % ( exc_type.__name__, exc_value )

  QtGui.QMessageBox.critical(None,"Error",
    "<html>A critical error has occured.<br/> "
  + "<b>%s</b><br/><br/>" % error
  + "It occurred at <b>line %d</b> of file <b>%s</b>.<br/>" % (line, filename)
  + "</html>")

  print "Closed due to an error. This is the full error report:"
  print
  print "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
  sys.exit(1)



# install handler for exceptions
sys.excepthook = handle_exception

这会捕获所有未处理的异常,因此您不需要尝试...除了代码顶层的块。

答案 1 :(得分:9)

你已经得到了很好的答案,我只想再添加一个多年来以多种语言为我提供的针对具体问题“如何干净地诊断,记录等,out of memory错误? ”。问题是,如果你的代码在足够的对象被销毁并且内存被回收之前得到控制,那么内存可能太紧,无法进行属性记录,gui工作等等 - 我们如何确保不会发生这种情况?

答案:建立一个紧急藏匿处,以便您知道可以在紧急情况下使用它:

rainydayfund = [[] for x in xrange(16*1024)]  # or however much you need

def handle_exception(e):
  global rainydayfund
  del rainydayfund
  ... etc, etc ...

答案 2 :(得分:2)

import sys, logging

logging.basicConfig(filename='/path/to/log/file', filemode='w')    
...

try:
   your_code_here()
except:
   logging.exception("My code failed") # logs exception to file
   # you define display_exception_in_ui as "def display_exception_in_ui(exc, tb):"
   display_exception_in_ui(*sys.exc_info()[1:]) # passes exception instance, traceback

答案 3 :(得分:0)

try:
    # blah blah The Main Loop, function, whatever...
except e:
    do_something_with(str(e))