2011-09-30 37 views

回答

5

您必须拿出错误代码和类别才能创建error_code对象。下面是一个例子,假设错误是由于另一主机拒绝连接:

error_code ec (errc::connection_refused, system_category()); 
return ec; 

也可以使用系统类别时传递errno值作为错误代码。例如:

#include <fstream> 
#include <cerrno> 
#include <boost/system/system_error.hpp> 

void foo() 
{ 
    ifstream file ("test.txt"); 
    if (!file.is_open()) 
    { 
     int err_code = errno; 
     boost::system::error_code ec (err_code 
      , boost::system::system_category()); 
     throw boost::system::system_error (ec, "cannot open file"); 
    } 
} 

不幸的是,这个库是很差documented,所以我建议你看看header files理出头绪。代码非常简单直接。

为了防止您的编译器支持C++ 11并且您愿意使用它,该功能使其成为标准。据我所知gcc 4.6.1已经有了。下面是一个简单的例子:

#include <cerrno> 
#include <system_error> 

std::error_code 
SystemError::getLastError() 
{ 
    int err_code = errno; 
    return std::error_code (err_code, std::system_category()); 
} 

void foo() 
{ 
    throw std::system_error (getLastError(), "something went wrong"); 
} 

一般来说,图书馆通过周围error_code对象,如果没有必要扔掉,用system_error扔描述系统故障异常。使用error_code而没有例外的另一个原因是当你需要在不同线程间发出错误信号时。但是C++ 11有a solution for propagating exceptions across threads

希望它能帮助!

相关问题