Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch and modify std::exception and subclasses, rethrow same type

I'd like to do sth like this:

try
{
  // ...
}
catch(const std::exception& ex)
{
  // should preserve ex' runtime type
  throw type_in_question(std::string("Custom message:") + ex.what());
}

Is that somehow possible without having to write a separate handler for each subtype?

like image 806
user1709708 Avatar asked Apr 10 '15 12:04

user1709708


1 Answers

What you're looking for would probably be something like this:

try {
    // ...
}
template <typename Exc>
catch (Exc const& ex) {
    throw Exc(std::string("Custom message:") + ex.what());
}

At least that's how we'd do such a thing in C++ typically. Unfortunatelly, you cannot write template code in a catch block like that. The best you could do is just add some runtime type information as a string:

try {
    // ...
}
catch (std::exception const& ex) {
    throw std::runtime_error(std::string("Custom message from ") +
                             typeid(ex).name() + ": " + ex.what());
}
like image 83
Barry Avatar answered Oct 06 '22 06:10

Barry