我是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
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
都无关紧要关于c++ - 当错误存在时,为什么我的程序不执行第二个catch块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36276006/