2021年4月1日星期四

What is the best way in C++ to tell a called function had an error with the return?

I have this function for reading a JSON file:

json read_json_from_file(const std::string &path) {    if(!file_exists(path)) {      // return error    }        json j = json(path);    return j;  }  

For the line where an error is returned what is the most C++ way of doing it?

I thought about returning NULL or nullptr.

I saw a project which used std::optional but it didn't make much sense for me. This would imply "this could possibly return something", instead of "this function could return an error". The code would be like the one below.

std::optional<json> read_json_from_file(const std::string &path) {    if(!file_exists(path)) {      return std::nullopt;    }        json j = json(path);    return j;  }  

And then, we would use this way:

auto s = "path/to/file.json";  auto j = read_json_file(s);  if(j == std::nullopt) { // std::nullopt as an example of using the std::optional    // do something because we got an error    std::cout << "error: could not open file " << s << std::endl;    return ERROR;  }  

This project doesn't use exceptions and we have no intention of doing that. Instead, I am looking for a way of returning errors and not losing context. See example below where I have no context after the function call:

std::optional<json> read_json_from_file(const std::string &path) {    if(!file_exists(path)) {      return std::nullopt;    }      if(get_file_extension(path) != "json") {      return std::nullopt;    }      json j = json(path);    return j;  }  

What is the best way to not lose context and don't use exceptions here?

https://stackoverflow.com/questions/66913307/what-is-the-best-way-in-c-to-tell-a-called-function-had-an-error-with-the-retu April 02, 2021 at 09:07AM

没有评论:

发表评论