当错误存在时,为什么我的程序不会执行第二个catch块?

时间:2016-03-29 05:18:12

标签: c++ exception exception-handling try-catch

我是try/catch异常处理的新手,我想知道为什么我的第二个catch块不会执行。 sec变量不应该介于0-59之间,因此我希望它说“#34;无效的第二个条目"”,但它并不是。谢谢!

#include <stdexcept>
#include <iostream>
#include <string>

using namespace std;


class BadHourError : public runtime_error
{
    public:
    BadHourError() : runtime_error("") {}
};

class BadSecondsError : public runtime_error
{
    public:
    BadSecondsError() : runtime_error("") {}
};

class Time
{
protected:
    int hour;
    int min;
    int sec;
public:
    Time()
    {
        hour = 0; min = 0; sec = 0;
    }

    Time(int h, int m, int s)
    {
        hour = h, min = m, sec = s;
    }

    int getHour() const
    {return hour;}

    int getMin() const
    {return min;}

    int getSec() const
    {return sec;}
};

class MilTime : public Time
{
protected:
    int milHours;
    int milSeconds;

public:
    MilTime() : Time()
    {
    setTime(2400, 60);
    }

    MilTime(int mh, int ms, int h, int m, int s) : Time(h, m, s)
    {
    milHours = mh;
    milSeconds = ms;
    getHour();
    getMin();
    getSec();
    }

    void setTime(int, int);
    int getHour(); //military hour
    int getStandHr(); 
};

void MilTime::setTime(int mh, int ms)
{
milHours = mh;
milSeconds = ms;
sec = milSeconds;
getSec();
}

int MilTime::getHour()
{
return milHours;
}

int MilTime::getStandHr()
{
return hour;
}


int main()
{
MilTime Object;

try
{
if ( (Object.getHour() < 0) || (Object.getHour() > 2359) ) throw BadHourError();
if ( (Object.getSec()  < 0) || (Object.getSec()  > 59  ) ) throw BadSecondsError();
}

catch (const BadHourError &)
{
cout << "ERROR, INVALID HOUR ENTRY";
}

catch (const BadSecondsError &)
{
cout << "ERROR, INVALID SECOND ENTRY";
}
return 0;
}

2 个答案:

答案 0 :(得分:1)

throw will return control to the next matching exception handler。在这种情况下,执行的下一个块将是您的catch (const BadHourError &),因此永远不会评估Object.getSec()。您在此处理的操作是正确的,它将throw,但如果您的第一个if声明throw取而代之,则会{。}}。

你可以这样做:

try
{
    if ( (Object.getHour() < 0) || (Object.getHour() > 2359) )
       throw BadHourError();
}
catch (const BadHourError &)
{
    cout << "ERROR, INVALID HOUR ENTRY";
}

try
{
    if ( (Object.getSec()  < 0) || (Object.getSec()  > 59  ) )
        throw BadSecondsError();
}
catch (const BadSecondsError &)
{
    cout << "ERROR, INVALID SECOND ENTRY";
}

现在他们将彼此分开处理,确保他们都得到测试;但是,你需要决定它是否值得测试。如果一小时无效,如果一切正确或无效,那有什么关系呢?您的课程可能无法正常运行,因此getSec() > 59如果getHour() > 2359

则无关紧要

答案 1 :(得分:0)

因为你的milHour是2400,所以在糟糕的时刻会抛出异常。