Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how can I handle any unhandled exception in an alternative way?

Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.

How can I do this?

like image 802
George Avatar asked Aug 05 '09 19:08

George


1 Answers

Use sys.excepthook to replace the base exception handler. You can do something like:

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

This catches all unhandled exceptions, so you don't need a try...except block at the top level of your code.

like image 60
Neil Avatar answered Oct 19 '22 05:10

Neil