我相信这是一个相当简单的问题,但是在catch异常发生时如何重新调用函数有点困惑?
我有这样的主线
while (state == true) //If there are exceptions thrown, you should report the problem and fairly seamlessly re-ask for a number
{
try
{
std::vector<int> numVec;
int i = getInteger();
numVec.push_back(i);
std::cout << i;
}
catch (const std::exception &e)
{
std::cout << "Something went wrong. How sad ..." << std::endl;
std::cout << "Problem in : " << e.what() << std::endl;
}
}
评论是我正在回答的当前问题。 我确实尝试了一次while循环(很像是草稿/我认为必须发生的事情(还要注意,我无法更改 getInteger()函数,因此我不包含它))
所以我需要的是,如果第一个 try-catch 掉落并且找到了 exception ,那么将重新调用 try 直到出现找到有效的输入。
答案 0 :(得分:1)
尝试一下。如果数字读取成功,则将变量state
设置为false并退出while
循环。否则,请打印适当的例外情况,然后要求重新输入数字。
std::vector<int> numVec;
while (state == true) {
try {
std::cout << "Please enter a number..." << std::endl;
int i = getInteger();
numVec.push_back(i);
std::cout << i;
state = false; // set status to false as read is successful
} catch (const std::exception &e) {
std::cout << "Something went wrong. How sad ..." << std::endl;
std::cout << "Problem in : " << e.what() << std::endl;
}
}