I'm experimenting with the concurrent run with promise functionality from Qt6. How can I catch, from the GUI thread, any exception thrown in the worker thread?
void MainWindow::on_pushButton_startTask_clicked()
{
auto lambda = [](QPromise<void>& promise)
{
// Cancel the task if requested
while (!promise.isCanceled())
{
// Do some long computation...
if (<something-has-failed>)
throw std::runtime_error("The task has failed");
}
};
this->future = QtConcurrent::run(lambda);
// Connect the watcher to the finished signal
connect(&this->watcher, &QFutureWatcher<void>::finished, this, &MainWindow::on_taskFinished);
this->watcher.setFuture(this->future);
}
void MainWindow::on_taskFinished()
{
// How to catch the exception here?
}
I've tried by doing the following two things:
- Adding
onFailed
in theon_taskFinished
:
void MainWindow::on_taskFinished()
{
this->future.onFailed([](const std::exception& ex)
{
std::cout << ex.what();
});
}
- Adding
onFailed
after callingQtConcurrent::run
:
void MainWindow::on_pushButton_startTask_clicked()
{
...
this->future = QtConcurrent::run(lambda)
.onFailed([](const std::exception& ex)
{
std::cout << ex.what();
});
...
}
In both cases the code passes from the onFailed
block, but the exception is not the one thrown from the lambda, it looks like an empty default excetion (maybe something from Qt?), whose what
content is Unknown exception
.