简体   繁体   中英

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(); is called. How can I fix this?

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

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:

The simple explanation is that you call isValid() also in the Date constructor. Which would be a logical thing to do. It is not inside a try {} block.

This fixed my issue entirely. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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