Bek
Bek

Reputation: 45

try/throw/catch in c++: what's wrong with my code?

Please can you check this code? What's wrong with try/catch/throw?

#include<iostream>
using namespace std;

int get_input();

int main() {

    int number, base_in, base_out;
    bool pass = 1;

    while(pass) {

        double number, base_in, base_out;

        try {

            cout << "What's your number? ";
            number = get_input();

            pass = 0;

        }
        catch(problem_type()) {
            cout << "Please, write inputs should be integer" << endl;
        }

    }

    return 0;
}


int get_input(bool target = 1) {

    double n;
    cin >> n;

    if(n != (int)n) throw problem_type();

    if(target) {
        if(n<1) throw problem_type();
    }

    return (int)n;

}

Upvotes: 0

Views: 188

Answers (2)

Rodrigo Gurgel
Rodrigo Gurgel

Reputation: 1736

When an exception is throw you'll get a in memory object with info about the exception... so it's necessary to take it as catch( const Type& error )

Why is it as a reference? Think of the possible caotic state that would be on memory on some situations, so MAKE a copy of would add complications and processing time, you could loose vital info. So that's why we take it as a reference.

Just 'point' to original piece of data.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

You catch by type. Like

catch(const problem_type&){ }

That is, if problem_type is type. I see no definition anywhere…

Upvotes: 3

Related Questions