【问题标题】:How to use try, throw and catch?如何使用 try、 throw 和 catch?
【发布时间】:2015-07-07 17:51:05
【问题描述】:

我正在尝试在一段代码中使用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 的新手,从我读到的内容来看,这可能不是它的正确应用,但我只是想尝试一下。

【问题讨论】:

  • 你使用什么编程语言?
  • 你能写一个更能反映你所问内容的问题标题吗?
  • 它们被称为异常是有原因的。如果您需要处理超出您控制/预期的异常类型,那么您将使用 try/catch。这不适用于验证用户输入,因为您可以预期他们将输入的内容,无论是否有效。只需编写一个返回错误消息/代码的验证例程。
  • 是否应该使用异常来处理用户输入错误引起了广泛而广泛的争论。对我来说,输入错误的用户并不例外。相反,它异常常见。
  • @DarylYoung - 你是对的,但是 OP 想要了解用法,而不是应用程序(并在他问题的最后一行中这么说)。看来他的实现是正确的,

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


【解决方案1】:

由于您没有提供运行代码或任何调试信息,我们不得不猜测(并自己编写程序)。见下文,它在 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;}
        }
    }
}

【讨论】:

    猜你喜欢
    • 2010-12-14
    • 2015-09-08
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多