繁体   English   中英

OOP 中的异常(try catch)c++

[英]exception (try catch ) c++ in OOP

我需要有关异常的帮助,我想为每个cout创建 Exception,我有这个方法,而且我对如何使用 try catch 为每个 if 创建异常感到有些困惑

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块, 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';
}

这是来自cppreference try 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";
    }
}

处理好异常的一个好方法是编写自己的异常。 这可以帮助您解决这个问题: 创建自定义异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM