1 [[!meta title="Qt: Throw exceptions from signals and slots"]]
2 [[!meta date="2010-07-08"]]
3 [[!meta author="rohieb"]]
4 [[!meta license="CC-BY-SA 3.0"]]
6 By default, you can not throw exceptions from signals and slots, and if
7 you try it, you get the following message:
9 > Qt has caught an exception thrown from an event handler. Throwing
10 > exceptions from an event handler is not supported in Qt. You must
11 > reimplement QApplication::notify() and catch all exceptions there.
13 So, what to do? The answer is simple: Overwrite the function `bool
14 QApplication::notify(QObject * receiver, QEvent * event)` so that it
15 catches all thrown exceptions. Here is some sample code:
19 #include <QApplication>
20 class MyApplication : public QApplication {
22 MyApplication(int& argc, char ** argv) :
23 QApplication(argc, argv) { }
24 virtual ~MyApplication() { }
26 // reimplemented from QApplication so we can throw exceptions in slots
27 virtual bool notify(QObject * receiver, QEvent * event) {
29 return QApplication::notify(receiver, event);
30 } catch(std::exception& e) {
31 qCritical() << "Exception thrown:" << e.what();
36 int main(int argc, char* argv[]) {
37 MyApplication app(argc, argv);
42 Of course, you can also inherit from `QCoreApplication` to get rid of
43 the `QtGui` dependency, or display a nice dialog box instead of printing
44 the messages to the console, or…
46 Found at: [Stack Overflow: Qt and error handling strategy][1]
48 [1]: http://stackoverflow.com/questions/1578331/qt-and-error-handling-strategy
50 [[!tag howto programming exceptions Qt signals slots]]