C++ 向我介绍boost::exception
我被要求使用boost::exception创建“可定制的异常框架”。到目前为止,我只使用我定义的简单异常。所以std::exception和boost::exception对我来说都是新事物。代码如下C++ 向我介绍boost::exception,c++,exception,boost,C++,Exception,Boost,我被要求使用boost::exception创建“可定制的异常框架”。到目前为止,我只使用我定义的简单异常。所以std::exception和boost::exception对我来说都是新事物。代码如下 #include <iterator> #include<string> #include <algorithm> #include<errno.h> struct My_exception:public virtual boost::excep
#include <iterator>
#include<string>
#include <algorithm>
#include<errno.h>
struct My_exception:public virtual boost::exception
{
};
int main()
{
std::string fileName="tmp.txt";
std::string mode="r";
try
{
if(fopen(fileName.c_str(),mode.c_str()))
std::cout << " file opened " << std::endl ;
else
{
My_exception e;
e << boost::errinfo_api_function("fopen") << boost::errinfo_file_name(fileName)
<< boost::errinfo_file_open_mode(mode) << boost::errinfo_errno(errno);
throw e;
}
}
catch(My_exception e)
{
// extract the details here //
}
return 1;
}
#包括
#包括
#包括
#包括
结构My_异常:公共虚拟boost::异常
{
};
int main()
{
std::string fileName=“tmp.txt”;
std::string mode=“r”;
尝试
{
if(fopen(fileName.c_str(),mode.c_str())
std::cout首先,您的代码有错误,例如,您无法编写以下代码:
e << boost::errinfo_api_function("fopen")
请参见第二个类型参数1,它是int
。同样,请检查其他错误类模板。在本文末尾,我已经给出了指向您正在使用的每个模板的链接
1.这个类模板似乎有两个版本,一个采用int
,另一个采用const char*
。与比较。感谢在注释中指出它的人。:-)
使用函数模板从boost::exception
获取数据
看看文件上怎么说
从数据库检索数据
异常对象,使用
获取错误信息函数模板
示例代码:
//since second type of errinfo_file_name is std::string
std::string fileError = get_error_info<errinfo_file_name>(e);
//since second type of errinfo_errno is int
int errno = get_error_info<errinfo_errno>(e);
//since second type of errinfo_file_open_mode is std::string
std::string mode = get_error_info<errinfo_file_open_mode>(e);
//since second type of errinfo_api_function is int
int apiError = get_error_info<errinfo_api_function>(e);
//因为第二种类型的errinfo\u文件名是std::string
std::string fileError=获取错误信息(e);
//因为第二种类型的errinfo\u errno是int
int errno=获取错误信息(e);
//因为第二种类型的errinfo_file_open_模式是std::string
字符串模式=获取错误信息(e);
//因为第二种类型的errinfo_api_函数是int
int APIRROR=获取错误信息(e);
为了更好地理解,请参见以下内容:
错误C2065:“errinfo_file_name”:未声明,但我包含了该文件#include@prabhakaran:您是否使用了正确的名称空间?@prabhakaran:writeboost::errinfo_file_name
,其他模板也一样!@Nawaz您是对的。现在我清除了这么多错误,除了这一个错误,这是什么意思“'':无法从'std::string'转换为'boost::errinfo_api_function'”errinfo_api_function
在boost 1.45中使用const char*
,
//since second type of errinfo_file_name is std::string
std::string fileError = get_error_info<errinfo_file_name>(e);
//since second type of errinfo_errno is int
int errno = get_error_info<errinfo_errno>(e);
//since second type of errinfo_file_open_mode is std::string
std::string mode = get_error_info<errinfo_file_open_mode>(e);
//since second type of errinfo_api_function is int
int apiError = get_error_info<errinfo_api_function>(e);