blag: make calendar start on monday
[www-rohieb-name.git] / blag / post / qt-throw-exceptions-from-signals-and-slots.mdwn
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"]]
5
6 By default, you can not throw exceptions from signals and slots, and if
7 you try it, you get the following message:
8
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.
12
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:
16
17 [[!format c """
18 #include <QtGui>
19 #include <QApplication>
20 class MyApplication : public QApplication {
21 public:
22 MyApplication(int& argc, char ** argv) :
23 QApplication(argc, argv) { }
24 virtual ~MyApplication() { }
25
26 // reimplemented from QApplication so we can throw exceptions in slots
27 virtual bool notify(QObject * receiver, QEvent * event) {
28 try {
29 return QApplication::notify(receiver, event);
30 } catch(std::exception& e) {
31 qCritical() << "Exception thrown:" << e.what();
32 }
33 return false;
34 }
35 };
36 int main(int argc, char* argv[]) {
37 MyApplication app(argc, argv);
38 // ...
39 }
40 """]]
41
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…
45
46 Found at: [Stack Overflow: Qt and error handling strategy][1]
47
48 [1]: http://stackoverflow.com/questions/1578331/qt-and-error-handling-strategy
49
50 [[!tag howto programming exceptions Qt signals slots]]
This page took 0.037545 seconds and 5 git commands to generate.