gpt4 book ai didi

c++ - 终止带有许多自定义错误消息的C++程序的最佳实践

转载 作者:行者123 更新时间:2023-12-03 08:19:29 28 4
gpt4 key购买 nike

我有一个带有很多“健全性检查”的代码,用于处理许多不同的用户错误,这些错误无法轻松地分类或分组为类别/异常。我发现自己编写了很多代码,例如下面的示例,在其中初始化结果变量,检查可能的错误,然后计算结果或退出程序。我认为这比if (x > 0) { return x; } else { terminate_with_error(...); };更好,但我想知道是否有更整洁的方法来进行设置。

#include <iostream>
#include <string>

void terminate_with_error(std::string err_string) {
std::cerr << err_string << std::endl;
exit(EXIT_FAILURE);
}

double stay_positive(double x) {
double result;
if (x < 0) {
terminate_with_error("Don't be so negative!");
} else {
result = x;
};
return result;
}

int main() {
stay_positive(-1);
return 0;
}

最佳答案

对于异常(exception)的有用性似乎存在误解。我将仅向您介绍此FAQ: Exceptions and Error handling,仅解决部分问题:

It's just that the pattern above is very repetitive and having to initialise things like double result just because I don't want the return statement in the if clause seems unnecessary, too. I just want to reduce the number of lines of code to write.



您无需执行任何操作。
double stay_positive(double x) {
double result;
if (x < 0) {
terminate_with_error("Don't be so negative!");
} else {
result = x;
};
return result;
}

坦白说,此功能确实很冗长。大部分可以删除:
double stay_positive(double x) {
if (x < 0) terminate_with_error("Don't be so negative!");
return x;
}

为了方便起见,您可以将 terminate_with_error转换为 terminate_if(bool,std::string),以便您可以编写
double stay_positive(double x) {
terminate_if(x<0,"Don't be so negative!");
return x;
}

但是,从长远来看,在出现问题时已经调用 exit是非常不灵活的。如果您遇到 x<0是错误但可以恢复的错误怎么办?在这种情况下,该功能应仅向调用者发出问题信号,并让调用者决定如何进行操作。您不必为此而重新发明轮子,因为有异常(exception)。如果您这样写:
double stay_positive(double x) {
if (x<0) throw "x must be positive";
return x;
}

调用者可以决定捕获异常并尝试从错误中恢复(当然,异常应包含的信息不仅仅是字符串,例如 x的值),也可以不捕获最终导致程序终止的信息。

关于c++ - 终止带有许多自定义错误消息的C++程序的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61011254/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com