Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a NULL string from a function c++

Tags:

c++

string

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!

like image 303
Asher Saban Avatar asked Dec 05 '22 22:12

Asher Saban


1 Answers

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.

like image 56
Björn Pollex Avatar answered Dec 29 '22 19:12

Björn Pollex