Skip to content

Instantly share code, notes, and snippets.

@satveersm
Created July 22, 2014 16:05
Show Gist options
  • Save satveersm/03b414dccd2972e24891 to your computer and use it in GitHub Desktop.
Save satveersm/03b414dccd2972e24891 to your computer and use it in GitHub Desktop.
//Exception handling in threads
//To propagate exceptions between threads you could catch them in the thread
//function and store them in a place where it can be accessed later.
std::mutex g_mutex;
std::vector<std::exception_ptr> g_exceptions;
void throw_function()
{
throw std::exception("something wrong happened");
}
void func()
{
try
{
throw_function();
}
catch(...)
{
std::lock_guard<std::mutex> lock(g_mutex);
g_exceptions.push_back(std::current_exception());
}
}
int main()
{
g_exceptions.clear();
std::thread t(func);
t.join();
for(auto& e : g_exceptions)
{
try
{
if(e != nullptr)
{
std::rethrow_exception(e);
}
}
catch(const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment