Fwd: [PyQt] Exception handling hook

Arve Knudsen arve.knudsen at gmail.com
Wed May 23 14:29:36 BST 2007


---------- Forwarded message ----------
From: Arve Knudsen <arve.knudsen at gmail.com>
Date: May 23, 2007 3:29 PM
Subject: Re: [PyQt] Exception handling hook
To: Sundance <sundance at ierne.eu.org>

On 5/23/07, Sundance <sundance at ierne.eu.org> wrote:
>
> 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.


It was hoping for some sort of mechanism to handle exceptions once they
propagate to the Qt event loop (managed by QApplication).

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.)


This is about how I've handled it so far in my own applicatio
n. But I found out the other day that this approach is not sufficient in all
cases unfortunately. In one part of my application, invoking a certain Qt
method (don't remember the exact situation at the moment) may cause a Python
callback to be invoked in return. So there are then the following layers: Qt
-> Python -> Qt -> Python. If an exception is raised in the last Python
layer, it is swallowed by the excepthook and a nice message box pops up, BUT
once control returns to the first Python layer (invoked by the event loop)
the flow is as if no exception has occurred (since the exception was already
handled).

Therefore,  the solution as far as I can tell is for PyQt to trap exceptions
in the outermost layer and allow client code to hook into this.

Arve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20070523/e31fda03/attachment.html


More information about the PyQt mailing list