C# 尝试{}Catch{}在C中不能正常工作#

C# 尝试{}Catch{}在C中不能正常工作#,c#,try-catch,C#,Try Catch,我有一个try{}catch{}用于我的用户输入的每一行内容,这是为了确保它的格式/范围/可接受性。然而,它似乎并没有。。。干得好!这里是我的一个例子 string userAnswer; bool errorHandling = true; while (errorHandling){ try{ userAnswer = Console.ReadLine(); if (u

我有一个
try{}catch{}
用于我的用户输入的每一行内容,这是为了确保它的格式/范围/可接受性。然而,它似乎并没有。。。干得好!这里是我的一个例子

string userAnswer;
        bool errorHandling = true;
        while (errorHandling){

            try{
                userAnswer = Console.ReadLine();

                if (userAnswer == "1") {
                  singleGrade.grapher(acount, bcount, ccount, dcount, ecount, fcount);
                }else{
                    if (userAnswer == "2"){
                      readIn.Classes(SingleGrade[1]);

                    }else{
                        if (userAnswer == "3"){
                           countAll.allGrades(multiGrade);
                        } else{
                           errorHandling = false;
                        }
                     }
                  }
              }
        catch (FormatException a){
                Console.WriteLine(a.Message);
                //Console.WriteLine("Error - please enter a number between 1 & 6.");
            }
    } // end of While loop 

如果有人能向我解释一下,当一个无效的数字被放置/格式不正确时,为什么没有发现错误。

没有因为输入了有效的字符串而引发
格式异常。例如,如果要将用户输入转换为整数,则会引发
FormatException
。但由于您将其作为字符串保留,因此不会引发异常

然而,由于您实际上只是试图限制用户输入,并且这里没有发生任何真正异常的情况,所以您可能应该通过应用程序逻辑来处理它

你真正想要的可能是这样的:

bool errorHandling = true;
while (errorHandling)
{
        string userAnswer = Console.ReadLine();   
        switch (userAnswer)
        {
            case "1":
              singleGrade.grapher(acount, bcount, ccount, dcount, ecount, fcount);
              errorHandling = false;
              break;

            case "2":  
              readIn.Classes(SingleGrade[1]);
              errorHandling = false;
              break;

            case "3":
              countAll.allGrades(multiGrade);
              errorHandling = false;
              break;

            // cases for 4, 5, and 6...

            default:
              Console.WriteLine("Error - please enter a number between 1 & 6.");
              break;
        }        
} // end of While loop 
public static int GetBoundedIntFromUser(int minVal, int maxVal)
{
    if (minVal >= maxVal)
    {
        throw new ArgumentException("minVal must be less than maxVal.");
    }

    int input;

    while (true)
    {
        Console.Write("Please enter a number from {0} to {1}: ", minVal, maxVal);

        if (int.TryParse(Console.ReadLine(), out input)
            && input >= minVal && input <= maxVal)
        {
            break;
        }

        Console.WriteLine("That input is not valid. Please try again.");
    }

    return input;
}

当数字无效时,您没有抛出和异常,您只是在处理一堆
if
语句-因此,由于没有
throw
语句,任何东西都不能命中
catch
语句,相反,您看到的是我们通俗地称之为“失败错误”的语句-逻辑正在超越它应该去的地方


如果您希望在输入无效时出现异常,只需在
If
语句的末尾添加一个
throw new FormatException
,这样您就可以得到一个“If we make it here a problem”行为。

原因是您正在抓取一个字符串,而不是试图将其转换为任何其他内容,因此没有
格式异常

我将不再使用
try/catch
进行输入验证,而是使用
Int
类型的
TryParse
方法

我通常会编写一个单独的函数,从用户那里获取经过验证的输入,然后从我的主代码中调用它。在这种情况下,由于你有上限和下限的要求,你可能会考虑写这样的东西:

bool errorHandling = true;
while (errorHandling)
{
        string userAnswer = Console.ReadLine();   
        switch (userAnswer)
        {
            case "1":
              singleGrade.grapher(acount, bcount, ccount, dcount, ecount, fcount);
              errorHandling = false;
              break;

            case "2":  
              readIn.Classes(SingleGrade[1]);
              errorHandling = false;
              break;

            case "3":
              countAll.allGrades(multiGrade);
              errorHandling = false;
              break;

            // cases for 4, 5, and 6...

            default:
              Console.WriteLine("Error - please enter a number between 1 & 6.");
              break;
        }        
} // end of While loop 
public static int GetBoundedIntFromUser(int minVal, int maxVal)
{
    if (minVal >= maxVal)
    {
        throw new ArgumentException("minVal must be less than maxVal.");
    }

    int input;

    while (true)
    {
        Console.Write("Please enter a number from {0} to {1}: ", minVal, maxVal);

        if (int.TryParse(Console.ReadLine(), out input)
            && input >= minVal && input <= maxVal)
        {
            break;
        }

        Console.WriteLine("That input is not valid. Please try again.");
    }

    return input;
}

正在引发其他一些异常,或者根本没有引发任何异常。将
FormatException
更改为
Exception
请发布一个简短但完整的程序来演示该问题。我们不知道
grapher
做了什么,也不知道您希望抛出
FormatException
什么。不过,我强烈建议您开始遵循.NET命名约定。不会引发异常。如果输入不是1、2或3,它只会出现在“errorhandling=false”行中。这看起来也像是您试图使用异常处理进行流控制的情况。用户输入超出1-6范围的数字并不是例外情况,因为您可以轻松检查它。整个异常块可以被if语句替换,并具有相同的效果strings@RufusL就.NET Framework而言,让我重新表述一下:“有效的”,就他的应用程序逻辑而言不是这样。那么,如果放置了字符串,那么将userAnswer更改为整数将引发异常?如果超出要求的范围怎么办?@OliSmart正确。如果超出所需的范围,则它将属于
开关
语句中的
默认
情况(或原始
If
块的最后
else
部分)。你可能想在那里处理它,要么自己抛出异常,要么显示错误消息。你需要自己检查。这并不是像Convert.ToInt32中的转换错误那样的异常情况。您将为4-6添加其他案例。不是1-6的所有内容都将由默认情况处理。最好使用int.TryParse()并同时删除异常处理。在这种情况下,这可能不是正确的异常类型。要么将字符串转换为另一种数据类型,让框架抛出异常,要么自己抛出一些自定义异常类型。但是从技术上讲,由于代码当前是编写的,因此不会发生
FormatException
。在这种情况下,异常处理是不必要的。当输入不是“1”、“2”或“3”时,只需显示一条错误消息就可以了