[英]Try and catch C++
我在尝试获得该代码中的正常工作时遇到了麻烦。 输入字符而不是数字时,它可以防止代码变得“循环”,但是,它不会给出cout <<“ Invalid entry”; 我在寻找回应。 我的教授建议,如果有更好的方法来捕获char,那么应该使用try and catch方法。 这是代码。 它用于分配FizzBuzz。
int main() {
int choice, choiceArray;
string userArray;
cout << "Welcome to the FizzBuzz program!"<< endl;
cout << "This program will check if the number you enter is divisible by 3, 5, or both." << endl;
try {
while(true) {
cout << "Enter a positive number"<< endl;
cin >> choice;
cout << endl;
if (choice % 3 == 0 && choice % 5 == 0) {
cout << "Number " << choice << " - FizzBuzz!" << endl;
break;
}
else if (choice % 3 == 0) {
cout << "Number " << choice << " Fizz!" << endl;
break;
}
else if (choice % 5 == 0) {
cout << "Number " << choice << " Buzz!" << endl;
break;
}
else {
cout << "Number entered is not divisible by 3 or 5, please try again." << endl;
}
}
}
catch (...) {
cout << "Invalid entry" << endl;
}
}
cin
默认不使用异常,您可以使用
cin.exceptions(std::ifstream::failbit);
没有例外,您还可以通过显式检查流状态来检测错误的输入,例如
if (cin >> choice) { /* ok */ }
else { /* bad input */ }
无论哪种方式,都必须重设故障状态( cin.clear()
)并从流( std::numeric_limits<std::streamsize>::max()
)中删除错误数据。
除了@Ben所说的之外 ,要catch
任何未指定的证据是一个相当糟糕的主意
catch (...) {
cout << "Invalid entry" << endl;
}
那绝对是绝对不得已的方法,您不能可靠地断定这是由于"Invalid entry"
或任何其他原因而引起的异常。
至少您应该先捕获一个std::exception
catch (const std::exception& e) {
cout << "Exception caught: '" << e.what() << "'!" << endl;
}
catch(...) {
cout << "Exception caught: Unspecified reason!" << endl;
}
并使用what()
函数提供更具体的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.