shahina
shahina

Reputation: 128

global try and catch block in qt

I am using Qt 4.8. Is there any way to have a global try and catch block for whole project. Example, if my application has two .cpp files. Is it possible way to catch exception across both .cpp files?

Upvotes: 0

Views: 1752

Answers (2)

Dmitry
Dmitry

Reputation: 3143

First of all, be warned that Qt doesn't play nice with exceptions. It was designed back in those days when exceptions were rather obscure feature of C++ so the use of exceptions was not generally considered a good practice for a whole bunch of implementation-related reasons.

Also be warned that as of Qt 5.7 the exception safety is not feature complete as the official doc currently tells:

Preliminary warning: Exception safety is not feature complete! Common cases should work, but classes might still leak or even crash.

If you use signal-slot connections within your classes, it's best to handle exceptions inside the slots which may throw them. As of Qt 5.7 not doing so is considered undefined behaviour.

If you just want to do some cleanup and/or error logging on any occasionally uncaught exception, you can either wrap the entire main() contents into try/catch block as the previous answer suggests or alternatively you can wrap the Qt's main event loop into such a block:

QApplication app(argc, argv);
...
try {
    app.exec();
}
catch (const std::exception &) {
    // clean up here, e.g. save the session
    // and close all config files.

    return 0; // exit the application
}

Upvotes: 1

Vladimir Bershov
Vladimir Bershov

Reputation: 2832

You can put in brackets the entire contents of your main() function as follows::

int main(int argc, char *argv[])
{
    int ret = 0;

    try    
    {
        QApplication a(argc, argv);

        QWidget w;
        w.show();

        ret = a.exec();
    }
    catch(...)
    {
        /* ... */
    }

    return ret;
}

See also: std::set_terminate()

Upvotes: 0

Related Questions