我正在尝试从使用 std::async
函数开始的函数中调用 future::get()
函数。在我抛出的 async
函数中,我可以在 future::get()
调用中捕获异常。但是,我在 get()
调用中遇到一个异常,该异常未在 catch block 中捕获,并且程序因未处理的异常而崩溃。我错过了什么?
#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"));
}
最佳答案
你不仅在抛出一个指向 std::exception
的指针在 AsyncMethodThrowsException
(没有理由这样做),你们都捕获了对异常的引用而不是指针,以及对 std::exception
的子类的引用在那; std::future::get()
抛出被调用函数中抛出的确切异常,而不是 std::future_error
.
还有一些其他的语法问题:
-
std::future<int> executionFuture
应该是std::future<void> executionFuture
-
std::future_status::future_status status
应该是std::future_status status
. -
std::exception
没有采用char const*
的构造函数或std::string
,这可能是一个编译器扩展。
总结一下:
#include <iostream>
#include <future>
void AsyncMethodThrowsExceptionTest();
void AsyncMethodThrowsException();
using namespace std;
int main()
{
AsyncMethodThrowsExceptionTest();
}
void AsyncMethodThrowsExceptionTest()
{
std::future<void> executionFuture;
try
{
executionFuture = async(launch::async, AsyncMethodThrowsException);
}
catch (...)
{
cout << "caught ex [1]";
}
std::future_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::exception& ex)
{
cout << "AsyncMethodThrowsExceptionTest catch block";
}
}
}
void AsyncMethodThrowsException()
{
throw runtime_error("Exception from AsyncMethodThrowsException");
}
关于c++ - std::future::get() 不捕获异步函数抛出和程序崩溃时的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557169/