Home > OS >  A question about c threads exception handling
A question about c threads exception handling

Time:11-26

Demo code:

#include <exception>
#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>

void func1() {
  std::cout << "Hello func1\n";
  throw std::runtime_error("func1 error");
}

int main() {
  try {
    std::future<void> result1 = std::async(func1);
    result1.get();
  } catch (const std::exception &e) {
    std::cerr << "Error caught: " <<e.what() << std::endl;
  }
}

Output:

Hello func1
Error caught: func1 error

It seems that the main function can catch exception from thread. But based on this question & answer , the main function should not be able to catch thread exception. It confused me. Maybe I mis-understand some information. Could anyone give some tips? Thanks in advance.

CodePudding user response:

First things first, std::async and std::thread are not the same thing at all. Moreover, std::async is not required to execute the callable into another thread, it depends on the launch policy you used.
I would suggest you to read the documentation about std::async.

But either way, any thrown exception are already handled by std::async and are stored in the shared state accessible through the returned std::future, which means the exceptions, if any, are rethrowned when you call std::future<T>::get() (which happens in the main thread in your case).

  • Related