I am currently learning / using c++, but I come from a Java background, so I apologize if this is a silly question. Below is some code representing the way I am handling errors generated by an external API. However, I am uncertain whether it would cause a memory leak when I assign a value to my error handling output parameter.
class ExceptionHandler {
private:
std::string _msg;
int _code;
public:
ExceptionHandler(std::string msg = "", int code = 0) :
_msg(msg),
_code(code)
{
}
int code() {
return _code;
}
std::string msg() {
return _msg;
}
}
//This method returns true if it was executed with no errors
//It returns false if an error occurred
bool foo(ExceptionHandler * errHandler = NULL) {
int sts;
//The API functions return 0 if completed successfully
//else they returns some error code
sts = some_api_func1();
if(sts != 0) { //An error occurred!
if(errHandler) {
ExceptionHandler handler("Error from func1",sts);
*errHandler = handler; //<--- Will this cause a memory leak since I would be losing errHandler's original value??
}
return false;
}
//My motivation for using exception handling this way is that I can
//set the handler's message based on what part it failed at and the
//code associated with it, like below:
sts = some_api_func2();
if(sts != 0) { //An error occurred!
if(errHandler) {
ExceptionHandler handler("Error from func2",sts); //<--- Different err message
*errHandler = handler; //<--- But does this cause a memory leak?
}
return false;
}
return true;
}
//Main method
int main() {
ExceptionHandler handler;
if(!foo(&handler)) {
std::cout << "An exception occurred: (" << handler.code() << ") " << handler.msg() << std::endl;
} else {
std::cout << "Success!" << std::endl;
}
}
Would the method 'foo()' cause a memory leak if an error occurred?
If so, how can I fix it? If not, how come it doesn't?
Is this a good way of handling errors?
Thank you in advance!
EDIT
I've learned that the above code would not generate a memory leak, but that the following code is a better way of handling errors (Thank you everyone!):
void foo() {
int sts;
sts = some_api_func1();
if(sts != 0)
throw ExceptionHandler("Error at func1",sts);
sts = some_api_func2();
if(sts != 0)
throw ExceptionHandler("Error at func2",sts);
}
int main() {
try {
foo();
std::cout << "Success!";
} catch(ExceptionHandler &e) { //<--- Catch by reference
std::cout << "Exception: (" << e.code() << ") " << e.msg();
}
}