function with try and catch infinite loop

Dec 21, 2020 at 10:22am
I am trying to call a function which has a try catch block inside, but it enters in some kind of infinite loop.If cin.fail() I want to catch the error and then read again the number,but instead it keeps going over and over into a infinite loop.

I would really appreciate some help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  void check_exception(cofetaria* add)
{
    int nr{ 0 };
    try {
        cin >> nr;
        if(cin.fail())
            throw 1;
        else {
            add->set_pret(nr);
        }
    } catch(int err) {
        cout << " You have to enter a number" << endl;
        return;
    }
}


and the function call is
 
check_exception(add);
Last edited on Dec 21, 2020 at 10:34am
Dec 21, 2020 at 10:37am
Hello tiberiu1998,

The problem I see here is that if "cin" fails because you did not enter a number it is left in its failed state and unusable the rest of the program.

Have a look at this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void check_exception(cofetaria* add)
{
    int nr{ 0 };

    try
    {
        cin >> nr;

        if (!cin)  // <--- A better choice for checking all the state bits. Not just 1.
            throw 1;
        else
        {
            add->set_pret(nr);
        }
    }
    catch (int err)
    {
        cout << " You have to enter a number" << endl;

        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

        return;
    }
}

The function would not cause an endless loop in its-self, but may be setting up an endless loop elsewhere because you did not reset the state bits on "cin".

For an endless loop problem I would look at the function call and what is around it.

Andy
Dec 21, 2020 at 11:02am
Thank you a lot, it worked !!
Dec 21, 2020 at 11:02am
Hello tiberiu1998,

I was thinking about the function and wondering if this is for a school assignment or something else?

If it is for school it helps to post the instructions that you were given, so those responding can know what you have to do and more to the point whar you have to use.

The "try/catch" works, but seems to be over done, unless it is required. There are other ways to check if "cin" has failed.

With out the rest of the code it is hard to say what would work best.

Andy
Dec 21, 2020 at 1:39pm
if (!cin) // <--- A better choice for checking all the state bits. Not just 1.
It's not really a "better" choice, they both do the same thing.
https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
... Specifically, returns !fail().
Last edited on Dec 21, 2020 at 1:39pm
Dec 22, 2020 at 9:20am
@Handy Andy,I was asked to solve the problem with try/catch, so it is ok the way it is now.
Dec 22, 2020 at 9:21am
@Ganado, thank you too!
Topic archived. No new replies allowed.