![](/img/trans.png)
[英]Throwing std::exception crashes Visual Studio 2013 IDE
[英]boost::thread program crashes on throwing std::exception
我很困惑為什么這個程序崩潰了。 這是整個計划
#include<fstream>
#include<string>
#include<iostream>
#include <exception>
#include <boost/thread/thread.hpp>
void func( const std::string& filename )
{
std::ofstream outFile( filename.c_str(), std::ios::binary);
if( !outFile.is_open() )
{
std::string err("Could not open file ");
err.append(filename);
err.append(" for writing");
throw std::exception(err.c_str());
}
}
int main()
{
std::string filename("xX:\\does_not_exist.txt");
try
{
boost::thread thrd(boost::bind(&func, filename ));
thrd.join();
// func( filename ); // calling this does not cause a crash
}
catch( const std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
return 0;
}
環境
Windows 7的
Visual Studio Express 2008
提升:嘗試1.44.0和1.46.1
鏈接(嘗試動態和靜態)
基本問題是,在當前標准中,不支持將異常從一個線程移動到另一個線程。 當異常在新創建的線程中保持未被捕獲時,它將到達堆棧的頂部並完成程序,就好像在main
未被捕獲的異常一樣。 考慮main
中的try
是在主線程的堆棧中,但異常是在完全不同的堆棧中。
這在boost線程中有記錄: http : //www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html#thread.thread_management.thread
在即將推出的標准中,支持將異常從一個線程移動到另一個線程,但您必須手動捕獲和移動或使用更高級別的構造,如std::future
。
你在線程中拋出一個異常,沒有周圍的catch塊來捕獲異常。 處理程序位於您創建線程的位置,但線程在其自己的單獨上下文中運行。
如果你想捕獲線程中拋出的異常,那么你需要在該線程內執行此操作。
Boost.Exception有一種在http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html中描述的線程之間傳輸異常的方法。
這也是即將推出的C ++ 0X標准的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.