Reputation: 111
I am new to try/catch
exception handling, and am wondering why my second catch
block will not execute. The sec
variable should not be between 0-59, so I'd like it to say "invalid second entry", but it doesn't. Thank you!
#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;
}
Upvotes: 0
Views: 81
Reputation: 7111
throw
will return control to the next matching exception handler. In this case, the next block executed will be your catch (const BadHourError &)
, so Object.getSec()
is never even evaluated. Your handling here is correct, and it will throw
but not if your first if
statement throw
instead.
You could do this instead:
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";
}
Now they will be handled separately from each other, ensuring they both get tested; however, you need to decide whether it's worth testing both. If an hour is invalid, what does it matter if everything is correct or invalid? Your class probably can't function well, so it doesn't matter if getSec() > 59
if getHour() > 2359
Upvotes: 1
Reputation: 1044
Because your milHour is 2400, so the exception is thrown for the bad hour.
Upvotes: 0