【问题标题】:exception (try catch ) c++ in OOPOOP 中的异常(尝试 catch)c++
【发布时间】:2020-01-18 16:15:09
【问题描述】:

我需要异常方面的帮助,我想为每个cout 生成异常,我有这个方法,但我有点困惑如何使用每个 if 的 try catch 来生成异常

istream & operator>>(istream & input, Date &date) 
{ 
    int day, mounth, year;
    cout << "please enter day , mounth year" << endl;
    input >> day >> mounth >> year;
    date.setDay(day);
    date.setMonth(mounth);
    date.setYear(year);
    if (day < 1 || day >31)
        throw "Illegal day for month should be number day - between 1 to 31" ;
    if (mounth < 1 || mounth > 12)
        throw "Illegal month should be number mount - between 1 to 12" ;
    if ((mounth == 4 || mounth == 6 || mounth == 9 || mounth == 11)
        && (date.day > 30))
        throw "Illegal day for month " ;
    if (year == 1 && mounth == 1 && day == 1)
        throw "please stop the while loop your date is 1/1/1" ;

        return input;
 }

【问题讨论】:

  • 它的try catch not actch 请通过stackoverflow.com/questions/134569/…
  • 所有这些throw 语句可以通过将它们移到Date 类方法中得到更好的处理。如果input 不是std::cin 怎么办?在那种情况下,用std::cout 提示用户是没有意义的。通常不鼓励在 operator&gt;&gt; 内提示用户。
  • @Remy Lebeau ,可以选择例如热来执行此操作

标签: c++


【解决方案1】:

在您的代码中,既没有 try 也没有 catch 块,throw 关键字需要像这样包装到 try 块中:

try {
    std::cout << "Throwing an integer exception...\n";
    throw 42;
} catch (int i) {
    std::cout << " the integer exception was caught, with value: " << i << '\n';
}

这是来自cppreferencetry catch 页面的示例,我建议您阅读此内容。

根据您的需要,您可以这样做:

int main()
{
    int day = 0;
    try {
        std::cin >> day;
        if (day < 1 || day >31)
            throw std::string("Illegal day for month should be number day - between 1 to 31");
    } catch (const std::string &error) {
        std::cout << "Catch error: " << error << "\n";
    }
}

编写自己的异常处理是一个很好的方法。 这可以帮助您解决这个问题:Creating custom exceptions

【讨论】:

  • catch (std::string error) - 我认为异常对象应该总是被const 引用捕获,所以catch (const std::string&amp; error)
  • 我先这样做了,然后编辑因为我不确定。感谢您的评论,我编辑了答案。
  • 但是为什么当我运行无效日期时,没有看到这个错误打印“一个月的非法日应该是数字日 - 介于 1 到 31 之间”
  • @danielshmushmayovich 我刚刚编辑了我的帖子,你需要抛出std::string 而不仅仅是throw "some string"。这是错误,现在它正在工作。
猜你喜欢
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 2020-01-10
相关资源
最近更新 更多