2
我想從使用std :: async函數啓動的函數調用future :: get()函數。在異步函數中,我正在拋出,以便在將來的:: get()調用中捕獲異常。然而,我在get()調用中遇到了一個異常,這個異常在捕獲塊中沒有被捕獲,並且程序因unhandeld異常而崩潰。我錯過了什麼?std :: future :: get()在異步函數拋出和程序崩潰時無法捕獲異常
#include "stdafx.h"
#include <iostream>
#include <future>
void AsyncMethodThrowsExceptionTest();
void AsyncMethodThrowsException();
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
AsyncMethodThrowsExceptionTest();
return 0;
}
void AsyncMethodThrowsExceptionTest()
{
std::future<int> executionFuture;
try
{
executionFuture = async(launch::async, AsyncMethodThrowsException);
}
catch(...)
{
cout << "caught ex [1]";
}
std::future_status::future_status status;
status = executionFuture.wait_for(std::chrono::milliseconds(500u));
if(status == std::future_status::deferred)
{
cout << "AsyncMethodThrowsException has not started";
}
else if(status == std::future_status::timeout)
{
cout << "AsyncMethodThrowsException timed out";
}
else if(status == std::future_status::ready)
{
cout << "AsyncMethodThrowsException successfully completed";
try
{
if(executionFuture.valid())
{
executionFuture.get();
}
}
catch(const std::future_error& ex)
{
cout << "AsyncMethodThrowsExceptionTest catch block";
}
}
}
void AsyncMethodThrowsException()
{
throw(new exception("Exception from AsyncMethodThrowsException"));
}
感謝您的及時響應。在我看來,拋出runtime_error(「來自AsyncMethodThrowsException的異常」);解決了這個問題。我正在使用Visual Studio 2012和我上傳的代碼編譯正常。另外,如果我確實趕上(...)它並不例外。 –
@RajibGhosal很好,catch(...)捕獲任何東西,但是你應該用'new'分配異常,只是拋出一個實際的對象。 – user657267