C ++抛出语句导致崩溃

时间:2013-09-12 16:39:55

标签: c++

目前我正在尝试学习如何使用异常,而且每当有无效数字时,我的当前任务就会崩溃。

isValid()中间的我的couts是调试语句,当我输入日期2013, 2, 29时崩溃,这是因为它是无效的一天,并且在throw std::exception();时崩溃叫做。我该如何解决这个问题?

Date.cpp

void Date::isValid() const
{
    std::cout << "Entering isValid()" << std::endl;
    if(_month < MIN_MONTH || _month > MAX_MONTH)
    {
        std::cout << "Before invalid month exception, in if" <<std::endl;
        throw std::exception();
    }

    std::cout << "Between ifs" << std::endl;
    int daysThisMonth = maxDay(_month, _year);

    if(_day < MIN_DAY || _day > daysThisMonth)
    {            
        std::cout << "Before invalid day exception, in if" << std::endl;
        throw std::exception();
    }
}

这是主要功能:

Main.cpp的

int main()
{
    int command = askForInt("\n\nEnter a custom date?\n1 - yes\n2 - no\n: ", 2, 1);
    while(command != 2)
    {   
        int year = askForInt("Year (1 - 5000): ", 5000, 1);
        int month = askForInt("Month: ", INT_MAX, 0);
        int day = askForInt("Day: ", INT_MAX, 0);
        Date whenEver(day, month, year);
        try
        {
            whenEver.isValid();
        }
        catch(std::exception& err)
        {
            std::cout << "The information you put in was invalid." << std::endl;
        }

        std::cout << "Your date: " << whenEver.toString() << std::endl;
        command = askForInt("\n\nEnter a custom date?\n1 - yes\n2 - no\n: ", 2, 1);
    }    

    return 0;
}

输出

    Enter a custom date?
    1 - yes
    2 - no
    : 1
    Year (1 - 5000): 2013
    Month: 2
    Day: 29
    Entering isValid()
    Between ifs
    Before invalid day exception, in if

这是崩溃的地方

1 个答案:

答案 0 :(得分:0)

@HansPissant说

简单的解释是,您也可以在isValid()构造函数中调用Date。这是合乎逻辑的事情。它不在try {}块内。

这完全解决了我的问题。谢谢!