Exception with variables

Asked

Viewed 45 times

0

I’m kind of new with exceptions treatment, what I wanted to do was read a variable in c++ and in case it’s different from the kind I declared to fall in catch.

int x;
try {
    cin >> x;
} catch (...) {
    cout << "Tipo errado" << endl;
}

In which the input could be anything from string and such.

  • And why would you do that? C++ programmers don’t do that? Is there a reason you want to use another language philosophy here?

2 answers

1


As you are using Cin, you should check your failbit, can do this in two ways:

if (!cin) {
     trow "Tipo errado";
}

OR

cin >> x;

while (!cin.good())
{
    cin.clear();
    cin.ignore(INT_MAX, '\n')
    cin >> x;
}

0

You would do so:

#include <iostream>
using namespace std;

int main() {
    int x = 0;

    try {
        cin >> x;
        if (x == 0) throw "Tipo errado";
    } catch(char const* msg) {
        cout << msg << endl;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.