当错误存在时,为什么我的程序不执行第二个catch块
Why wont my program execute the second catch block, when the error exists?
我是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,所以为坏的小时抛出异常。
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 为什么程序运行时我的第二个循环不执行?
- 如何在C 对向量的第二个元素上执行较低的操作
- 当执行此代码中的第二个语句时,内部会发生什么
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- 当我在程序中输入第二个值时,它将我带到第三值,而无法正确执行
- 停止直接执行主应用程序并从第二个应用程序执行它
- OpenCv:未执行第二个cvPutText
- 为什么我的程序不执行第二个catch块
- 当错误存在时,为什么我的程序不执行第二个catch块
- 空白或不执行任何操作的三元运算符的第二个或第三个参数
- 在 2 精灵上运行 2 个 CCSequence 的第二个精灵不会执行动作