0

I'm sure this is something simple, but wasn't able to find any other posts clearly specifying this, though I'm sure there must be one buried somewhere.

In C++, when using a try catch block in the below manner, how can I append a string variable to the error message?

I get an unhandled exception when trying to do this. Is it something to do with what type is passed back? Appears to be returning a string versus a char*. if that is correct, would that cause the issue? How would I adjust for this? I tried adding an additional catch (const string my_msg), but that did not work, either.

string msg = "message";
try{
    if (...)
        throw "My error " + msg;
    }
catch (const char* my_msg){
    cerr << my_msg << endl;
}
CGutz
  • 537
  • 2
  • 7
  • 20

1 Answers1

3

"My error " + msg is an operation that concatenates a const char* string and an std::string. This operation results in a temporary variable of type std::string. Therefore, the thrown variable must be caught with a catch clause of type std::string.

catch (const std::string& my_msg){
    cerr << my_msg << endl;
}

Still, it is better practice to have your exceptions derive from std::exception. You don't need to create your own exception class though, as there is std::runtime_error and its derivations, which provides useful classifications of common runtime exceptions.

There are many cases where you need to have a distinct type for your exceptions, often of which may be project or domain specific. In C++11, making your own exception type is as easy as this

struct my_exception : std::runtime_error {
    using std::runtime_error::runtime_error;   // Inherit runtime_error's constructors
};

This uses C++11's inheriting constructors.

Sylvester
  • 91
  • 3
  • 11
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94