Qt/C++ Error handling

Override QCoreApplication::notify() and add try-catch there. That, and something in main() covers most cases in my experience.

Here’s sort-of how I do it. Note that I’m using C++ RTTI here, not Qt’s version, but that’s just for convenience in our apps. Also, we put up a QMessageBox with the info and a link to our log-file. You should expand according to your own needs.

bool QMyApplication::notify(QObject* receiver, QEvent* event)
{
    try {
        return QApplication::notify(receiver, event);
    } catch (std::exception &e) {
        qFatal("Error %s sending event %s to object %s (%s)", 
            e.what(), typeid(*event).name(), qPrintable(receiver->objectName()),
            typeid(*receiver).name());
    } catch (...) {
        qFatal("Error <unknown> sending event %s to object %s (%s)", 
            typeid(*event).name(), qPrintable(receiver->objectName()),
            typeid(*receiver).name());
    }        

    // qFatal aborts, so this isn't really necessary
    // but you might continue if you use a different logging lib
    return false;
}

In addition, we use the __try, __except on Windows to catch asynchronous exceptions (access violations). Google Breakpad could probably serve as a cross-platform substitute for that.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)