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

Why wont my program execute the second catch block, when the error exists?

本文关键字:执行 第二个 catch 程序 我的 存在 错误 为什么      更新时间:2023-10-16

我是try/catch异常处理的新手,想知道为什么我的第二个catch块不会执行。sec变量不应该在0-59之间,所以我希望它说"无效的第二个条目",但它没有。非常感谢。

#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;
}

throw将控制权返回给下一个匹配的异常处理程序。在这种情况下,执行的下一个块将是您的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

都无关紧要

因为您的milHour是2400,所以为坏的小时抛出异常。

相关文章: