User Tools

Site Tools


c:c_threads:troubleshooting:program_crashes:not_handling_exceptions_in_background_threads

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

c:c_threads:troubleshooting:program_crashes:not_handling_exceptions_in_background_threads [2021/06/09 11:16] – created peterc:c_threads:troubleshooting:program_crashes:not_handling_exceptions_in_background_threads [2021/06/09 11:17] (current) peter
Line 60: Line 60:
  
 <code cpp> <code cpp>
 +#include<iostream>
 +#include<thread>
 +#include<exception>
 +#include<stdexcept>
 +
 +static std::exception_ptr globalExceptionPtr = nullptr;
 +
 +void HelloWorld()
 +{
 +  try
 +  {
 +    std::this_thread::sleep_for(std::chrono::milliseconds(100));
 +    throw std::runtime_error("Catch me in MAIN");
 +  }
 +  catch (...)
 +  {
 +    // Set the global exception pointer in case of an exception.
 +    globalExceptionPtr = std::current_exception();
 +  }
 +}
 +
 +
 +int main()
 +{
 +  std::thread t1(HelloWorld);
 +  t1.join();
 +  if (globalExceptionPtr)
 +  {
 +    try
 +    {
 +      std::rethrow_exception(globalExceptionPtr);
 +    }
 +    catch (const std::exception &ex)
 +    {
 +      std::cout << "Thread exited with exception: " << ex.what() << "\n";
 +    }
 +  }
 +  return 0;
 +}
 </code> </code>
  
c/c_threads/troubleshooting/program_crashes/not_handling_exceptions_in_background_threads.1623237390.txt.gz · Last modified: 2021/06/09 11:16 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki