Is there a way to have exceptions work indefinitely?

巧了我就是萌 提交于 2021-01-29 22:38:46

问题


I have been trying to take an input from the user. I want to ensure that the input meets my requirements for the rest of the code for which I have used a try and catch block.

However, after only one time catching, it aborts the code. I want to ensure that after catching error it actually goes back to the input function for as many times until the user gives the program a valid input. Is there a way to do that except not using try catch blocks altogether?

Here's the code:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

long num; // I need num as global

long get_input()
{
    string input;
    long number;

    cout << "Enter a positive natural number: ";
    cin >> input;

    if ( !(stol(input)) ) // function for string to long conversion
        throw 'R';

    number = stol(input);

    if (number <= 0)
        throw 'I';

    return number;
}

int main()
{
    try
    {
        num = get_input();
    }
    catch (char)
    {
        cout << "Enter a POSTIVE NATURAL NUMBER!\n";
    }

// I want that after catch block is executed, the user gets chances to input the correct number 
// until they give the right input.

    return 0;
}

回答1:


You need explicitly write such a handling, e.g. via loop:

int main()
{
    while (1) {
        try
        {
            num = get_input();
            return 0; // this one finishes the program
        }
        catch (char)
        {
            cout << "Enter a POSTIVE NATURAL NUMBER!\n";
        }
    }
}


来源:https://stackoverflow.com/questions/62607424/is-there-a-way-to-have-exceptions-work-indefinitely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!