I have a problem similar to this poster, but I can't figure out what I should do in my case. Instead of calling exit(EXIT_FAILURE) on a separate thread, I want the main thread to handle the exception. To me this looks clean and organized. I tried this:

Qt Code:
  1. #include <QString>
  2. #include <iostream>
  3. #include <QtConcurrentRun>
  4. #include <qtconcurrentexception.h>
  5. using std::cerr;
  6. using std::ostream;
  7.  
  8. class MyException : public QtConcurrent::Exception {
  9. public:
  10. MyException(const QString& msg) { _msg = msg; }
  11. virtual ~MyException() throw() {}
  12.  
  13. const QString& msg() { return _msg; }
  14.  
  15. void raise() const { throw *this; }
  16. Exception *clone() const { return new MyException(*this); }
  17. private:
  18. QString _msg;
  19. };
  20.  
  21. void separateThread() {
  22. int i = 0;
  23. while (i < 10000)
  24. ++i;
  25.  
  26. throw MyException("This exception should be caught by the main thread");
  27. }
  28.  
  29. int main() {
  30. QFuture<void> otherThread = QtConcurrent::run(&separateThread);
  31.  
  32. int i = 0;
  33. while (i < 10)
  34. ++i;
  35.  
  36. try {
  37. otherThread.waitForFinished();
  38. } catch (MyException& e) {
  39. std::cerr << "QUITTING WITH ERROR\n" << e.msg().toStdString() << std::endl;
  40. }
  41.  
  42. return 0;
  43. }
To copy to clipboard, switch view to plain text mode 

I kept in mind that

When using QFuture, transferred exceptions will be thrown when calling the following functions:
- QFuture::waitForFinished()
- QFuture::result()
- QFuture::resultAt()
- QFuture::results()
The exception, however, isn't handled and the program crashes. What am I doing wrong here?