Qt / C ++ event loop exception handling

I have an application based on QT and on many third-party libs. In some cases, some exceptions occur.

In a native Qt application, this leads to the termination or termination of the application. Often the main data model is still untouched, since I store it in pure Qt without external data.

Thus, I think that I could simply recover by informing the user that an error has occurred in this process, and he should save now or even decide to continue working on the main model.

Currently, the program just silently comes out without even telling the story.

+4
source share
2 answers

As stated in the Qt documentation here , Qt is currently not completely safe for everyone. The "Restore from exceptions" section on this page describes the only thing you can do in a Qt application when an exception occurs is to clear and exit the application.

Given that you use third-party libraries that throw exceptions, you need to catch them on the border between the external library and Qt code and handle them there - as pointed out in a Caleb comment. If an error is to be propagated in a Qt application, this must be done either by returning an error code (if possible) or by posting an event.

+5
source

Sometimes it is very difficult to catch all the exceptions. If one exception accidentally slips, the following helps. Inherit from QApplication and override the notify() function as follows

 bool MyApplication::notify( QObject * receiver, QEvent * event ) { try { return QApplication::notify(receiver, event); } catch(...) { assert( !"Oops. Forgot to catch exception?" ); // may be handle exception here ... } return false; } 

Then replace the QApplication in your main() with your own class. All events and slots are slots through this function, so that all exceptions can be caught and your application will become stable.

+5
source

Source: https://habr.com/ru/post/1308235/


All Articles