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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With