C# Try/Catch 来自枚举列表的用户输入检查

C# Try/Catch from User Input Checking for Enum List

我正在努力学习 C#,但我真的很吃力。我非常需要帮助。我的任务是将语句包装在 try/catch 块中并打印“请输入一周中的实际日期。”如果发生错误,到控制台。我设法根据枚举确定用户输入是否为真,但我无法捕捉到错误的部分。任何帮助将不胜感激。

我在单独的 class 中制作了名为 OneWeek 的枚举列表,这是我的代码:

        Console.WriteLine("Please enter the current name of the day.");
        string input = Console.ReadLine();
        string test = input.ToLower();
        OneWeek.DaysOfTheWeek dayParse;
        bool inputParse = Enum.TryParse(test, out dayParse);
        try
        {

            if (inputParse == true)
            {
                Console.WriteLine("Thank God it's " + input);
            }

        }

        catch (FormatException)
        {
            Console.WriteLine("Please enter an actual day of the week.");
            
        }

        catch (Exception)
        {
            Console.WriteLine("Please enter an actual day of the week.");
            
        }
        Console.ReadLine();
        return;

感谢所有回答的人!尝试了所有建议,它有所帮助。我还在建议的线程上找到了答案。你们让我很开心。谢谢!

这是我的代码的最终结果。只是改变了一些变量,但目标是一样的。

try
        {
            Console.WriteLine("Please enter the current name of the day.");
            string input = Console.ReadLine();
            string test = input.ToUpper();

            OneWeek.DaysOfTheWeek day;

            if (Enum.TryParse<OneWeek.DaysOfTheWeek>(test, out day))
            {
                Console.WriteLine("You are right! Today is  " + test + "!");
            }

            else
            {
                throw new OverflowException();
            }
     

        }

        catch (OverflowException)
        {
            Console.WriteLine("Please enter an actual day of the week.");
            
            
        }

        Console.ReadLine();
        return;

您实际上不会得到异常,因为您正在相当安全地处理您的值(好)。

如果你真的想要异常,你需要抛出一个:

if (inputParse == true)
{
    Console.WriteLine("Thank God it's " + input);
}
else 
{
   throw new FormatException("Please Enter a real day of the week");
}

然后我也会将 catch 更改为:

catch (FormatException fex)
{
    Console.WriteLine(fex.Message);            
}

或者,或者,不太安全地处理枚举:

try
{
   OneWeek.DaysOfTheWeek dayParse = Enum.Parse(test);
}
catch (Exception ex)
{
   // write error
}
    Console.WriteLine("Please enter the current name of the day.");
    string input = Console.ReadLine();
    string test = input.ToLower();
    if(Enum.TryParse(test, out var dayParse))
        Console.WriteLine("Thank God it's " + input);
    else
        Console.WriteLine("Please enter an actual day of the week."); 
  
    Console.ReadLine();
    return;