试着抓住C++

Try and catch C++

本文关键字:C++      更新时间:2023-10-16

我无法让尝试和捕获在此代码中正常工作。当输入字符而不是数字时,它可以防止代码变得"循环",但是,它不会给出 cout<<"无效条目";我正在寻找的回应。我的教授暗示,如果有更好的方法来捕捉应该有一个 int 的字符,我愿意接受建议,请使用 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()功能提供更具体的信息。

相关文章:
  • 没有找到相关文章