try / throw / catch in c ++:我的代码出了什么问题?

时间:2012-10-02 16:36:15

标签: c++ try-catch

请查看此代码吗? 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;

}

2 个答案:

答案 0 :(得分:3)

按类型捕捉。像

catch(const problem_type&){ }

也就是说,如果problem_type是类型。我看不到任何定义...

答案 1 :(得分:0)

当抛出异常时,你会得到一个内存对象,其中包含有关异常的信息......因此有必要将其作为catch( const Type& error )

为什么它作为参考?想想在某些情况下可能存在的内存状态,因此制作副本会增加复杂性和处理时间,您可能会丢失重要信息。这就是我们将其作为参考的原因。

只是'指向'原始数据。