c++ - C++ 中让函数返回错误或值的最佳方法是什么?
问题描述
我有这个函数来读取 JSON 文件:
json read_json_from_file(const std::string &path) {
if(!file_exists(path)) {
// return error
}
json j = json(path);
return j;
}
对于返回错误的行,最 C++ 的做法是什么?
我想过返回NULL
或nullptr
。
我看到了一个使用过的项目,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++ 的做法是什么?
throw
一个例外。如果这不是一个选项,则返回 a std::variant<json, errorInfo>
,其中errorInfo
是您需要描述错误的任何内容(错误代码、错误消息字符串、具有有关错误的多个详细信息的类/结构等)。
推荐阅读
- git - 标签是否包含先前提交的所有更改?
- java - postgresql(设置角色用户)命令如何在 SSM 项目中使用?
- python - 如何使用提示在海龟图形中设置颜色和尺寸?
- python - 不能从模块导入函数而是导入模块,那么module.function是成功的
- safari - safari 通知权限在重新启动后总是返回“默认”,即使网站之前允许通知
- python - Python从列表中获取int?
- heroku - 上传文件到heroku时返回503服务不可用
- python - 仅计算大图中局部邻域的亲和度的有效方法
- java - 当我使用 gradle5.0 构建我的项目时,它导致 java.lang.OutOfMemoryError: Java heap space。如何解决?
- apache-spark - Spark SQL - 由于空值而长时间运行的1个任务是连接键