[PyQt] Exception handling hook

Sundance sundance at ierne.eu.org
Wed May 23 14:11:06 BST 2007


Arve Knudsen wrote:

> Is it possible to register a hook with QApplication in order to be
> notified of an unhandled exception?

Hi Arve,

Exceptions live in the Python realm, so they have nothing to do with 
QApplication as far as I know.

You can install an exception handler with sys.excepthook.

Here's a PyQt3 example (which might also work with PyQt4, I haven't 
tested):


def handle_exception(exc_type, exc_value, exc_traceback):

  filename, line, dummy, dummy = \
    traceback.extract_tb(exc_traceback).pop()
  filename = os.path.basename(filename)
  error = "%s: %s" % (str(exc_type).split(".")[-1], exc_value)
  
  QMessageBox.critical(None, "ERROR",
    "There has been an error: "
    + "<b>%s</b> " % error
    + "on line %d, file %s" % (line, filename))
  

You can (and probably should) close your application then.

You can install this handler with:
sys.excepthook=handle_exception

(Since the handler uses QMessageBox, install it AFTER instanciating your 
QApplication.)

Bye,

-- S.


More information about the PyQt mailing list