繁体   English   中英

导致崩溃的C ++投掷语句

[英]C++ Throw Statement Causing Crashes

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

我在isValid()中间的提示是调试语句,当我将日期2013、2、29放入时2013, 2, 29它崩溃是因为它是无效的一天,并且在throw std::exception();时崩溃了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

这是它崩溃的地方

@HansPassant写道:

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

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

暂无
暂无

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

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