Introduce boost::exception to me
I am asked to create "customizable exception framework" using boost::exception. Till date I used only simple exceptions defined by me. So std::exception,boost::exception are new to me. The code is below.
#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;
}
Now, I want to know that how to extract the data from that caught exception. Can anybody guide me in the path of boost::exception
First of all, your code has error, for example you cannot write this:
e << boost::errinfo_api_function("fopen")
Because errinfo_api_function
can be used with int
only. So do something like this:
e << boost::errinfo_api_function(100) //say 100 is error code for api error
See the second type parameter to errinfo_api_function
1, it's int
. Similarly, check other error class templates. I've given the link to each of them you're using, at the end of this post!
1. It seems there're two version of this class template, one which takes int
, other which takes const char*
. Compare version 1.40.0 errinfo_api_function with version 1.45.0 errinfo_api_function. Thanks to dalle who pointed it out in the comment. :-)
Use get_error_info function template to get data from boost::exception
.
See what boost::exception documentation says,
To retrieve data from a boost::exception object, use the get_error_info function template.
Sample code:
//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);
See these for better understanding:
- errinfo_file_name
- errinfo_errno
- errinfo_file_open_mode
- errinfo_api_function
精彩评论