string receiveFromServer();
this function returns a string that was received from some server. If there was an error along the way (including protocol), i want to return a NULL string. However, this doesn't work in c++ (unlike java). i tried:
string response = receiveFromServer();
if (response==NULL) {
cerr << "error recive response\n";
}
but its not legal. Since an empty string is also legal to return, what can i return that will indicate the error?
thank you!
You can throw an exception to indicate an error.
try {
std::string response = receiveFromServer();
} catch(std::runtime_error & e) {
std::cerr << e.what();
}
Then you would need a throw std::runtime_error("Error receive response")
somewhere in receiveFromServer()
.
It is often considered good practice (though some might disagree) to create your own exception-classes that derive from std::runtime_error
to enable clients to catch your errors specifically.
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