[英]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.