Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a message to std::exception?

Tags:

c++

I would like to do the following:

std::string fileName = "file";
std::ifstream in(fileName.c_str());
in.exceptions(std::istream::failbit);

try
{
    loadDataFrom(in);
}
catch (std::ios_base::failure& exception)
{
    std::string location = std::string(" in file\n") + fileName;
    // append the "location" to the error message;
    throw;
}

How can I append the error message to an exception?

like image 604
Martin Drozdik Avatar asked May 22 '14 13:05

Martin Drozdik


2 Answers

You can throw a new exception, with the augmented message:

throw std::ios_base::failure(exception.what() + location,
                             exception.code());

Edit: The second parameter exception.code() is from C++11.

2nd edit: Note that, if your caught exception is from a sub-class of std::ios_base::failure, you will lose parts of it, using my suggestion.

like image 90
lrineau Avatar answered Nov 13 '22 22:11

lrineau


I think you can only take what() convert it to string, append, and re-throw the exception.

catch (std::ios_base::failure& exception)
{
    std::string location = std::string(" in file\n") + fileName;
    std::string error(exception.what());
    throw std::ios_base::failure(error+location);
    // throw std::ios_base::failure(error+location, exception.code()); // in case of c++11
}

Remember that since c++11 failure got a 2nd argument. You rather want to pass it too.

like image 22
luk32 Avatar answered Nov 13 '22 22:11

luk32