如何使用try,throw和catch?

时间:2015-04-28 18:11:10

标签: c++ exception exception-handling try-catch throw

我试图在一段代码中使用try, throw and catch来测试输入是否良好。这是我到目前为止所拥有的;

 while(loop > 0){
    try{
        cout << "Please input the x and y centre point: separated by a space" << endl;
        cin >> Cx >> Cy;
        if(isalpha(Cx)){cin.clear(); cin.ignore();throw 1;}
        if(isalpha(Cy)){cin.clear(); cin.ignore();throw 2;}

        cout << "Please input the side length" << endl;
        cin >> side1;
        if(isalpha(side1)){cin.clear(); cin.ignore();throw 3;}
        if(side1 <= 0){cin.clear(); cin.ignore();throw 4;}

        loop = 0;
    }
    catch(int err){
        if(err == 1){cout << "X center co-ordinate should be a number" << endl;}
        if(err == 2){cout << "Y center co-ordinate should be a number" << endl;}
        if(err == 3){cout << "The length should be a number" << endl;}
        if(err == 4){cout << "The length should be greater than 0" << endl;}
    }
}

当我运行此项并输入o 0作为中心点时,程序仍会输出Please input the side length然后The length should be greater than 0,最后循环返回以请求新的中心点。

我应该如何改变这一点,以便在边长线之前读出正确的错误信息(理想情况下不会输出边长线)?

由于

我是使用try, throw and catch的新手,而且从我所读到的内容来看,这可能不适合它,但我只想尝试一下。

1 个答案:

答案 0 :(得分:0)

由于您没有提供正在运行的代码或任何调试信息,我们不得不猜测(并自行编写程序)。请参阅下文,该文件在cygwin 4.9.2 / Windows 7下完美运行。修改您的程序以匹配或发布完整的非正确代码以进行其他尝试。

#include <iostream>
#include <locale>

using namespace std;

int main (int argc, char **argv)
{
    int loop = 1;
    char Cx, Cy;
    char side1;
    while(loop){
        try{
            cout << "Please input the x and y centre point: separated by a space" << endl;
            cin >> Cx >> Cy;

            if(isalpha(Cx)){cin.clear(); cin.ignore();throw 1;}
            if(isalpha(Cy)){cin.clear(); cin.ignore();throw 2;}

            cout << "Please input the side length" << endl;
            cin >> side1;
            if(isalpha(side1)){cin.clear(); cin.ignore();throw 3;}
            if(side1 <= 0){cin.clear(); cin.ignore();throw 4;}

            loop = 0;
        }
        catch(int err){
            if(err == 1){cout << "X center co-ordinate should be a number" << endl;}
            if(err == 2){cout << "Y center co-ordinate should be a number" << endl;}
            if(err == 3){cout << "The length should be a number" << endl;}
            if(err == 4){cout << "The length should be greater than 0" << endl;}
        }
    }
}