【问题标题】:How can I handle an exception in C#? [duplicate]如何处理 C# 中的异常? [复制]
【发布时间】:2018-05-11 08:37:37
【问题描述】:

如果double.Parse(string) 尝试解析无效值(例如字符串而不是数字),我正在尝试处理异常以避免我的程序崩溃。这是我得到的:

do
{
    //asking customer the amount of shirts he would like to buy any shirts they want.
    numbershirtString = Console.ReadLine(); // customer types in amount of shirts they want.
    numbershirts = double.Parse(numbershirtString);

    keepLooping = true;

    if (numbershirts < 10)
    {
        Console.WriteLine("You would be buying " + numbershirts + " shirts");
        keepLooping = false;
    }

    if (numbershirts > 10)
    {
        Console.WriteLine("You cannot order more than 10 shirts. Please try again.");
        keepLooping = true;
    }

} while (keepLooping);

感谢您的帮助。提前谢谢!

【问题讨论】:

  • C# 7.0 if (double.TryParse(s, out var i)) { use i } else { do something without i}

标签: c# exception


【解决方案1】:

也许这对你来说有点高级,但如果你心情愉快,你可以定义一个处理用户输入解析的类。这样您就可以将该逻辑与您的主程序分开(请参阅separation of concerns)。

public class UserEntry
{
    private readonly string _originalValue;

    public UserEntry(string input)
    {
        _originalValue = input;
    }

    public bool IsInt
    {
        get
        {
            return int.TryParse(_originalValue, out var dummy);
        }           
    }

    public int ToInt()
    {
        return ToInt(default(int));
    }

    public int ToInt(int defaultValue)
    {
        int result;

        bool ok = int.TryParse(_originalValue, out result);
        return ok ? result : defaultValue;
    }

    public override string ToString()
    {
        return _originalValue;
    }

    static public implicit operator UserEntry(string input)
    {
        return new UserEntry(input);
    }

    static public implicit operator Int32(UserEntry input)
    {
        return input.ToInt();
    }
}

如果我们使用隐式转换运算符,它会使事情变得非常简单。例如,所有这些现在都是合法的:

UserEntry entry = Console.ReadLine();
if (!entry.IsInt) continue;
if (entry < 10) return entry;

如果我们将此应用于您的示例,它会缩短您的代码一点,并且可以说也使其更清晰。

public class Program
{
    private const int MaximumOrder = 10;

    public static void Main()
    {
        var n = AskForNumberOfShirts();
        Console.WriteLine("OK, I'll order {0} shirts.", n);
    }

    public static int AskForNumberOfShirts()
    {
        while (true)
        {
            Console.WriteLine("Enter the number of shirts to order:");
            UserEntry entry = Console.ReadLine();
            if (!entry.IsInt)
            {
                Console.WriteLine("You entered an invalid number.");
                continue;
            }
            if (entry > MaximumOrder)
            {
                Console.WriteLine("{0} is too many! Please enter {1} or fewer.", entry, MaximumOrder);
                continue;
            }
            return entry;
        }
    }
}

注意事项:

  1. 我怀疑你可以订购半件衬衫,所以我使用int 而不是double 来存储衬衫的数量。
  2. 我重构了逻辑分支以使用机会回报,a.ka.守卫模式。 See this article for why I do this
  3. 我将常量值10 提取为它自己的符号MaximumOrder。这应该会让你在作业上加分。

输出:

Enter the number of shirts to order:
22
22 is too many! Please enter 10 or fewer.
Enter the number of shirts to order:
sdlfkj
You entered an invalid number.
Enter the number of shirts to order:
9
OK, I'll order 9 shirts.

Working example on DotNetFiddle

【讨论】:

    【解决方案2】:

    要处理异常,在 C# 中就像在其他语言中一样,您可以使用 try..catch 块。 看最简单的语法:

    try
    {
        //Try to run some code.
    }
    catch
    {
        //Do something if anything excepted.
    }
    

    如果您有兴趣检索哪个异常破坏了代码:

    try
    {
        //Try to run some code.
    }
    catch (Exception ex)
    {
        //Do something ex was thrown.
    }
    

    如果您将 ex 的类型更改为继承基类 Exception 的类型,您将只处理该类型的所有异常:

    try
    {
        //Try to run some code.
    }
    catch (StackOverflowException ex)
    {
        //Do something ex was thrown because you overflowed the stack.
    }
    

    但不要谈论您可以在 Google 上找到更多信息的 try..catch 块,我建议您使用方法 double.TryParse(string, out double)。 它的语法与double.Parse 有点不同,但实际上它以不同的方式执行相同的操作。 如果您的输入有效,则返回true,否则返回false,而在第一个参数中您只需传递string 输入,第二个参数需要对结果变量的输出引用:

    double x = 0;
    string number = "125.3";
    if (double.TryParse(number, out x))
        Console.WriteLine("Your number is " + x.ToString());
    else
        Console.WriteLine("Your input isn't valid");
    

    【讨论】:

      【解决方案3】:

      请改用double.TryParse()。它根据结果返回true of false

      double val;
      bool success = double.TryParse("red", out val);
      if(success)
      {
          // val contains a parsed value
      }
      else
      {
          // could not parse
      }
      

      【讨论】:

      • 返回值取决于输入;o)
      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-27
      • 2019-07-25
      • 2016-11-02
      相关资源
      最近更新 更多