Introduce boost :: exception for me

I am encouraged to create a “custom exception framework” using boost :: exception. So far, I have used only the simple exceptions defined by me. Therefore 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 how to extract data from this caught exception. Can anyone direct me on boost :: exception path

+3
source share
1 answer

First of all, your code has an error, for example, you cannot write this:

e << boost::errinfo_api_function("fopen")

Because it errinfo_api_functioncan only be used with int. So do something like this:

  e << boost::errinfo_api_function(100) //say 100 is error code for api error

. errinfo_api_function 1 it int. , . , , !

< > 1. , , int, , const char*. 1.40.0 errinfo_api_function 1.45.0 errinfo_api_function. dalle, .: -) >


get_error_info boost::exception.

, boost:: exception,

boost:: , get_error_info.


:

//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);

:

+6

Source: https://habr.com/ru/post/1790141/


All Articles