当前位置: 动力学知识库 > 问答 > 编程问答 >

Simple try catch looping solution for c++

问题描述:

I can't see why this fails. Why does it loop forever after throwing the error?

bool undone;

do

{

undone = false;

try

{

o.spr(); // function throwing error E object

}

catch(E &r)

{

undone = true;

cout << r.reason << endl;

}

}

while(undone);

Here is the function:

void spr()

{

E r;

int n;

cout << " put n : "<<endl;

cin >> n;

if (cin.fail())

{

r.reason="fail !!";

throw r;

}

cout << " your n is : "<< n;

}

网友答案:

Your problem is recovering after the error.

First you have to clear the error flag from cin using cin.clear(). Then you have to read the bad input so it doesn't cause an error next time:

void spr()
{
    E r;
    int n;
    cout << " put n : "<<endl;
    cin >> n;
    if (cin.fail())
    {
        cin.clear(); // clear the error flag

        std::string bad_input;
        cin >> bad_input; // skip over bad input

        // now it is safe to re-use cin

        r.reason="fail !!";
        throw r;
    }
    cout << " your n is : "<< n;
}

Probably a better way to skip the bad input:

void spr()
{
    E r;
    int n;
    cout << " put n : "<<endl;
    cin >> n;
    if (cin.fail())
    {
        cin.clear(); // clear the error flag
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip over bad input

        r.reason="fail !!";
        throw r;
    }
    cout << " your n is : "<< n;
}

The cin.ignore() function skips over the maximum possible number of input characters until it gets to an end of line '\n' character.

网友答案:

In case o.spr() throws, you set undone to true. Then condition in while() is checked, and it's true, so it loops, tries to call o.spr() again, and so on... Reconsider your undone flag and its value.

分享给朋友:
您可能感兴趣的文章:
随机阅读: