Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Thread Exception Handling

I'm trying to throw an exception within a thread and allow the calling process to catch it. However, it seems that this will cause the entire application to crash. See test code attached never prints either exit statement.

1 #include <boost/thread.hpp>
2 #include <iostream>
3
4 void wait(int seconds)
5 {
6       boost::this_thread::sleep(boost::posix_time::seconds(seconds));
7 }
8
9 void thread()
10 {
11       for (int i = 0; i < 5; ++i)
12       {
13           wait(1);
14           std::cout << i << std::endl;
15       }
16       throw;
17 }
18
19 int main()
20 {
21     try
22     {
23         boost::thread t(thread);
24         t.join();
25         std::cout << "Exit normally\n";
26     }
27     catch (...)
28     {
29         std::cout << "Caught Exception\n";
30     }
31 }
like image 892
Greg Avatar asked Nov 17 '11 04:11

Greg


1 Answers

Have a look at boost exception: Transporting of Exceptions Between Threads. This approach has worked well for me.

like image 188
Ralf Avatar answered Sep 28 '22 00:09

Ralf