Tuesday, February 24, 2009

exit(0)




Say that your application has subclassed QApplication and that you have some evaluation logic in the constructor that needs to exit the application if some condition is not met like so:


int main(int argc, char **argv) {
MyQApplication app(argc, argv);
return app.exec();
}

MyQApplication::MyQApplication(int argc, char** argv) :
QApplication(argc, argv) {

// want to be able to exit here
}


So what's the issue? Well QCoreApplication::exit() and QCoreApplication::quit()
(which is the same as exit(0)) needs the event loop to be up and running. As the documentation for QCoreApplication::exit() says says: "If the event loop is not running, this function does nothing."

Now from a design perspective exiting from the constructor like this is probably not the best way to go about things. But, for the sake of argument say that you really have to. And have to without refactoring the code.

So far the only two options I've come across that let's you keep your old design is qFatal() and std::exit(). However, they both leave some to be desired. qFatal() will print and "Aborted" at the end and that is no good if you have an internationalized application. std::exit(0) will require reaching outside of Qt, which is fine, but you need to update the compiler include path and that could open up issues when compiling on different (non-standard) systems.

Now if you're not to lazy a re-design is in place. I posed the question to the qt-interest mailing list and got a couple of good responses.

Arnold Krille suggested to create a bool MyQApplication::shouldRun() and then check before calling app.exec() like so:


int main(int argc, char **argv) {
MyQApplication app(argc, argv);

if (app.shouldRun())
return app.exec();
}


Scott Aron Bloom pointed out that throwing an exception is considered better practice then calling exit() directly.


MyQApplication::MyQApplication(int argc, char** argv) :
QApplication(argc, argv) {

if(errorConditionExisted)
throw ...
}

0 comments: