아래 코드에서 동일한 예외를 다시 throw 한 후에 예외를 catch하려고 시도하지만 동일한 결과를 얻을 수 없습니다. 나는 current_exception()을 통해 현재 teptr 상태를 보존했기 때문에 무엇이 잘못되었는지 확신하지 못한다. 스레드가 연속 루프에서 실행되므로 해당 값이 큰 2에 도달하면 catch 블록이 실행되고 제어가 루프에서 벗어나지 만 예상대로 계속 첫 번째 시도에서 다른 catch 블록에 도달 할 수 없습니다.스레드에서 예외를 throw하는 것이 예상 결과를 제공하지 않습니다.
#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'에 할당합니다. 어딘가에서'join '을 할 의향이 있습니까? –
거기에 가입 할 필요는 없습니다. – user2997518
당신은 어떻게 생각하니? –