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:
#include <QString>
#include <iostream>
#include <QtConcurrentRun>
#include <qtconcurrentexception.h>
using std::cerr;
using std::ostream;
class MyException : public QtConcurrent::Exception {
public:
MyException(const QString& msg) { _msg = msg; }
virtual ~MyException() throw() {}
const QString& msg() { return _msg; }
void raise() const { throw *this; }
Exception *clone() const { return new MyException(*this); }
private:
};
void separateThread() {
int i = 0;
while (i < 10000)
++i;
throw MyException("This exception should be caught by the main thread");
}
int main() {
QFuture<void> otherThread = QtConcurrent::run(&separateThread);
int i = 0;
while (i < 10)
++i;
try {
otherThread.waitForFinished();
} catch (MyException& e) {
std::cerr << "QUITTING WITH ERROR\n" << e.msg().toStdString() << std::endl;
}
return 0;
}
#include <QString>
#include <iostream>
#include <QtConcurrentRun>
#include <qtconcurrentexception.h>
using std::cerr;
using std::ostream;
class MyException : public QtConcurrent::Exception {
public:
MyException(const QString& msg) { _msg = msg; }
virtual ~MyException() throw() {}
const QString& msg() { return _msg; }
void raise() const { throw *this; }
Exception *clone() const { return new MyException(*this); }
private:
QString _msg;
};
void separateThread() {
int i = 0;
while (i < 10000)
++i;
throw MyException("This exception should be caught by the main thread");
}
int main() {
QFuture<void> otherThread = QtConcurrent::run(&separateThread);
int i = 0;
while (i < 10)
++i;
try {
otherThread.waitForFinished();
} catch (MyException& e) {
std::cerr << "QUITTING WITH ERROR\n" << e.msg().toStdString() << std::endl;
}
return 0;
}
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?
Bookmarks