简体   繁体   中英

Appending a string when throwing an error in C++

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;
}

"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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM