6

Where should i use an except block in order to log exceptions of a QApplication?

This doesn't seem to work:

app = QtGui.QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
try:
    eventLoop = app.exec_()
except Exception, e:
    log.exception(str(e))

as the exception won't even reach that block.

Cœur
  • 37,241
  • 25
  • 195
  • 267
iTayb
  • 12,373
  • 24
  • 81
  • 135

2 Answers2

5

Throwing exceptions from an event handler is not supported in Qt. You must reimplement QApplication::notify() and catch all exceptions there.

Overwrite the function bool QApplication::notify(QObject * receiver, QEvent *event) so that it catches all thrown exceptions.

You can implement like this.

virtual bool notify(QObject * receiver, QEvent * event) 
{
     try 
     {
     return QApplication::notify(receiver, event);
     } 
     catch(std::exception& e) 
     {
      qDebug() << "Exception thrown:" << e.what();
     }
}
ScarCode
  • 3,074
  • 3
  • 19
  • 32
  • That wouldn't work as QApplication.notify catches C++ exceptions, and I need to catch python exceptions. – iTayb May 20 '12 at 21:24
  • 1
    How can I do it? I mean, should I translate this code to Python or make a c++ file and make python import it? I'm lost, since this code is C++ and we are talking about python. – Rafael Oliveira Oct 11 '13 at 16:18
0

I solved it by overriding the excepthook, as seen in the following answer: Logging All Exceptions in a pyqt4 app

Community
  • 1
  • 1
iTayb
  • 12,373
  • 24
  • 81
  • 135