【发布时间】:2018-05-31 01:34:01
【问题描述】:
在下面的代码 sn-p 中,我试图在重新抛出相同但无法实现相同后捕获异常。我不确定出了什么问题,因为我已经通过 current_exception() 保存了当前的 teptr 状态。线程在连续循环中运行,因此一旦其值达到更大的 2,则执行 catch 块并且控制超出循环,但仍然如预期的那样,我无法在第一次尝试时到达另一个 catch 块。
#include <boost/thread.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
#include <boost/exception/all.hpp>
#include <exception>
using namespace std;
boost::exception_ptr teptr;
class myexception : public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
class ABC
{
public:
void start();
};
void ABC::start()
{
int i = 0;
cout << "running the thread" << std::endl;
while (1)
{
try
{
std::cout << "value of " << i << '\n';
if (i > 2)
{
throw boost::enable_current_exception(myex);
}
i++;
}
catch (exception& e)
{
cout << "actual exception is" << e.what() << '\n';
teptr = boost::current_exception();
break;
//throw myex;
}
}
}
int main()
{
ABC abc;
boost::thread thread_point;
while (1)
{
boost::thread thread_point;
thread_point = boost::thread(&ABC::start, abc);
if (teptr) {
try {
boost::rethrow_exception(teptr);
}
catch (const std::exception &ex)
{
std::cerr << "Thread exited with exception: " << ex.what() << "\n";
exit(0);
}
}
}
}
【问题讨论】:
-
在分配给
teptr之前,这里没有什么可以阻止if (teptr)运行。你的意思是在某个地方做一个join吗? -
那里不需要加入。
-
是什么让你这么想?
-
join 阻塞,需要等待线程完成。
标签: c++ multithreading exception boost