我应该只对无效输入使用异常处理吗?
Should I use Exception handling for just invalid input?
我有这个例子:
int main() {
int val{};
bool stop = false;
char c;
while (!stop) {
std::cout << "val: ";
try {
if (!(std::cin >> val)) {
throw std::runtime_error("bad input");
}
std::cout << val << " : " << val * val << std::endl;
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
std::cout << "retry\?\n>>" << std::endl;
std::cin >> c;
if (c != 'y' && c != 'Y')
stop = true;
}
}
}
代码工作正常,但我想知道我应该在实际程序中使用它吗?因为我看到了一些替代方案:将输入作为字符串然后使用转换为整数类型。
- 我的问题是:我应该对无效输入(例如应该为整数的字符)使用异常处理,还是只起诉字符串和转换?
显示有问题的 try/throw/catch 的代码片段:
try {
if (!(std::cin >> val)) {
throw std::runtime_error("bad input");
}
std::cout << val << " : " << val * val << std::endl;
}
catch (std::exception& e) {
对于提供的示例,您不会在 真实世界代码 中使用 try/throw/catch。通常,您更喜欢阅读和理解最简单的代码,对于这种情况,完全避免异常处理并使用 if/else 会更简单:
if ((std::cin >> val)) {
std::cout << val << " : " << val * val << std::endl;
}
else {
我有这个例子:
int main() {
int val{};
bool stop = false;
char c;
while (!stop) {
std::cout << "val: ";
try {
if (!(std::cin >> val)) {
throw std::runtime_error("bad input");
}
std::cout << val << " : " << val * val << std::endl;
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
std::cout << "retry\?\n>>" << std::endl;
std::cin >> c;
if (c != 'y' && c != 'Y')
stop = true;
}
}
}
代码工作正常,但我想知道我应该在实际程序中使用它吗?因为我看到了一些替代方案:将输入作为字符串然后使用转换为整数类型。
- 我的问题是:我应该对无效输入(例如应该为整数的字符)使用异常处理,还是只起诉字符串和转换?
显示有问题的 try/throw/catch 的代码片段:
try {
if (!(std::cin >> val)) {
throw std::runtime_error("bad input");
}
std::cout << val << " : " << val * val << std::endl;
}
catch (std::exception& e) {
对于提供的示例,您不会在 真实世界代码 中使用 try/throw/catch。通常,您更喜欢阅读和理解最简单的代码,对于这种情况,完全避免异常处理并使用 if/else 会更简单:
if ((std::cin >> val)) {
std::cout << val << " : " << val * val << std::endl;
}
else {