0

I would like to abort an application execution (done with Qt) with an error message in case there was a problem regarding it.

with abort(); it was not working with me.

Do you have any suggestions?

MelMed
  • 1,702
  • 5
  • 17
  • 25

1 Answers1

1

The simplest way is to exit the application's event loop with a non-zero result code, and show a message box afterwards. You can either re-spin the event loop manually, or let the messagebox's static method do it for you.

#include <QPushButton>
#include <QMessageBox>
#include <QApplication>

QString globalMessage;

class Failer : public QObject {
    Q_OBJECT
public:
    Q_SLOT void failure() {
        globalMessage = "Houston, we have got a problem.";
        qApp->exit(1);
    }
};

int main(int argc, char ** argv) {
    QApplication app(argc, argv);
    QPushButton pb("Fail Me");
    Failer failer;
    failer.connect(&pb, SIGNAL(clicked()), SLOT(failure()));
    pb.show();
    int rc = app.exec();
    if (rc) {
        QMessageBox::critical(NULL, "A problem has occurred...", 
                              globalMessage, QMessageBox::Ok);
    }
    return rc;
}

#include "main.moc"
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • Actually, you can just throw `QString` and catch it within `main`, then show message box using that string. Which is simpler. – SigTerm Oct 17 '13 at 14:48
  • @SigTerm: Had you have tried it, you'd know it doesn't work, because on the call stack between the slot where you throw it, and `main`, there's often a bunch of system API functions. [You need to catch the exception in a reimplementation of `QCoreApplication::notify`](http://stackoverflow.com/a/19149041/1329652) – Kuba hasn't forgotten Monica Oct 17 '13 at 14:55
  • @KubaOber: Actually, I tried it and use regularly. In half of the cases it works by default. In other half you need to reimplement notify. Which is fairly easy. – SigTerm Oct 17 '13 at 15:15
  • To have portable code that always works, you need to reimplement notify and catch exeptions there. You don't need to do anything in `main` unless you want to handle stuff thrown by whatever constructors/methods you invoke in `main` itself. I mean, yeah, `exec()` could possibly throw if it runs out of memory itself, but that's got nothing to do with your code. – Kuba hasn't forgotten Monica Oct 17 '13 at 15:19