首页 > 解决方案 > C++ 中让函数返回错误或值的最佳方法是什么?

问题描述

我有这个函数来读取 JSON 文件:

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

对于返回错误的行,最 C++ 的做法是什么?

我想过返回NULLnullptr

我看到了一个使用过的项目,std::optional但对我来说没有多大意义。这意味着“这可能会返回一些东西”,而不是“这个函数可能会返回错误”。代码将类似于下面的代码。

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

然后,我们将使用这种方式:

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

该项目不使用异常,我们也无意这样做。相反,我正在寻找一种返回错误而不丢失上下文的方法。请参阅下面的示例,其中函数调用后我没有上下文:

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

不丢失上下文并且不在这里使用异常的最佳方法是什么?

标签: c++c++17

解决方案


对于返回错误的行,最 C++ 的做法是什么?

throw一个例外。如果这不是一个选项,则返回 a std::variant<json, errorInfo>,其中errorInfo是您需要描述错误的任何内容(错误代码、错误消息字符串、具有有关错误的多个详细信息的类/结构等)。


推荐阅读