簡體   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