Home > howto, programming > Qt: Throw exceptions from signals and slots

Qt: Throw exceptions from signals and slots

By default, you can not throw exceptions from signals and slots:

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

So, what to do? The answer is simple: Overwrite the function bool QApplication::notify(QObject * receiver, QEvent * event) so that it catches all thrown exceptions. Here is some sample code:

#include <QtGui>
#include <QApplication>
class MyApplication : public QApplication {
public:
  MyApplication(int& argc, char ** argv) :
    QApplication(argc, argv) { }
  virtual ~MyApplication() { }

  // reimplemented from QApplication so we can throw exceptions in slots
  virtual bool notify(QObject * receiver, QEvent * event) {
    try {
      return QApplication::notify(receiver, event);
    } catch(std::exception& e) {
      qCritical() << "Exception thrown:" << e.what();
    }
    return false;
  }

int main(int argc, char *argv[]) {
  MyApplication app(argc, argv);
  // ...
}

Of course, you can also inherit from QCoreApplication to get rid of the QtGui dependency, or display a nice dialog box instead of printing the messages to the console, or…

Found at: Stack Overflow: Qt and error handling strategy


Flattr this

About these ads
Categories: howto, programming Tags: , , ,
  1. March 22, 2012 at 22:39

    I do have the notify system setup in a QApplication, yet, when I throw from a slot of a dynamically loaded plugin I am still getting the same error… (throwing from other places, like one of the plugin core methods works just fine..)

  2. November 19, 2012 at 01:33

    Where such file is located? I’m having the very same problem here with LMMS and I’m feeling adventurous.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: