简体   繁体   English

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

[英]C++ Throw Statement Causing Crashes

Currently I'm trying to learn how to use exceptions, and my current assignment is just crashing every time there is an invalid number. 目前,我正在尝试学习如何使用异常,并且每当有无效数字时,我当前的任务就会崩溃。

My couts in the middle of isValid() are debug statements, when I put in the date 2013, 2, 29 it crashes, it is because it is an invalid day, and it crashes when throw std::exception(); 我在isValid()中间的提示是调试语句,当我将日期2013、2、29放入时2013, 2, 29它崩溃是因为它是无效的一天,并且在throw std::exception();时崩溃了throw std::exception(); is called. 叫做。 How can I fix this? 我怎样才能解决这个问题?

Date.cpp 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();
    }
}

This is being caught in the main function here: 这被捕获在这里的主要功能中:

Main.cpp 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;
}

Output 输出量

    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

This is where it crashes 这是它崩溃的地方

@HansPassant wrote: @HansPassant写道:

The simple explanation is that you call isValid() also in the Date constructor. 简单的解释是您也可以在Date构造函数中调用isValid() Which would be a logical thing to do. 这将是合乎逻辑的事情。 It is not inside a try {} block. 它不在try {}块中。

This fixed my issue entirely. 这完全解决了我的问题。 Thanks! 谢谢!

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

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