[PyKDE] Exceptions in callbacks

Pete Ware ware at cis.ohio-state.edu
Mon Feb 5 14:17:05 GMT 2001


Bruce Sass <bsass at freenet.edmonton.ab.ca> writes:

> I think you will find the Python way more flexible once you get your
> head around it.
Yes, I understand that, and yes I wish I was good enough to anticipate
all exceptions -- but I'm not.  Let me try again.  As a python
programmer, one would expect the following to act as a fail safe, the
world is going to hell so do something bit of code:

	try:
		app.exec_loop ()
	except:
		print 'Caught an exception!'


where the "app.exec_loop()" is the PyQt event loop.  No matter what
happens, the code "print 'Caught an exception!'" will never execute
since exec_loop() catches _all_ Python exceptions.

I understand (and agree) that this is desirable for most applications
and I'm not asking to change that.  What I am looking for is a way to
allow my code to execute when an (unanticipated) exception happens.

What I don't think is reasonable is that everywhere I create a push
button, or a menu item, or a slider, or _any_ time I connect a
qt.SIGNAL() with a callable that I should have to wrap exception
handling code around that callable.  Note: I am not saying I don't
catch errors in my code (callables).  What I am saying is that I catch
the errors I expect but when an unexpected error occurs current
PyQt behaviour is for the error to silently disappear (effectively
since stdout is not visible).

--pete
----------------------------------------------------------------------
#! /bin/env python
#				-*- Python -*-
import sys
import qt

class Test (qt.QFrame):
	def __init__ (self, parent = None, name = ''):
		qt.QFrame.__init__ (self, parent, name)
		top = qt.QPushButton ('Exception', self)
		top.setMinimumSize (top.sizeHint ())
		top.connect (top, qt.SIGNAL ('clicked()'), self.raise_exception)

	def raise_exception (self):
		raise 'An exception.  How can I catch this?'
		
w = None
def test ():
	global w
	app = qt.QApplication (sys.argv)

	w = Test (None, 'Table')
	app.setMainWidget (w)
	w.show ()

	return app

if __name__ == '__main__':
	app = test ()
	try:
		app.exec_loop ()
	except:
		print 'Caught an exception!'




More information about the PyQt mailing list