私はtry/catch
例外処理の初心者で、なぜ2番目のcatch
ブロックが実行されないのだろうと思っています。 sec
変数は0〜59の間であってはなりません。したがって、「無効な2番目のエントリ」と言いたいのですが、そうではありません。ありがとうございました!エラーが存在する場合、私のプログラムは2番目のcatchブロックを実行しません。なぜですか?
#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;
}
この単純なプログラムでは、 'if((Object.getSec()<0)||(Object。 getSec()> 59))cout << try/catchがどのように動作するかを学習していない限り、 "ERROR、INVALID SECOND ENTRY"; – immibis