如何在 C# 中双精度为 Null/Empty 时创建异常?

How to create an exception when a double is Null/Empty in C#?

我正在用 C# 创建二十一点。当游戏开始时,我的代码要求用户 "Please, make a bet." 但是,用户可能只是单击 "enter",应用程序就会崩溃。我试着破例:

  Console.WriteLine("Please, make a bet");
        bet = Convert.ToDouble(Console.ReadLine());
        try
        {
            bet = 0;
        }
        catch (System.FormatException)
        {
            Console.WriteLine("You have to bet in order to play");
        }
        catch (Exception e)
        {
            Console.WriteLine("You have to bet in order to play");
        }

但是,它似乎无法正常工作,而且我的应用程序还是崩溃了。 bet 变量是双精度变量,因此我不能像使用字符串时那样使用 if(double.IsNullOrEmpty(bet)){//Something};double.IsNan(bet) 也不能作为条件。那么,当 double 为 null/empty 时,如何进行异常处理?

您没有检查是否为空

if(bet == null){
Console.WriteLine("You have to make a bet");
}else{
Console.WriteLine("That");
}

抛出异常的行,在本例中 bet = Convert.ToDouble(Console.ReadLine()) 必须在 try 块内,以便捕获异常。

try
{
   bet = Convert.ToDouble(Console.ReadLine());
}
catch (System.FormatException)
{
   Console.WriteLine("You have to make a bet.");
}
catch (Exception)
{
   Console.WriteLine("You have to make a bet.");
}

或者,您可以使用 Double.TryParse 来解析用户的输入。

也许像...

Console.WriteLine("Enter your bet.");
while (!Double.TryParse(Console.ReadLine(), out bet))
{
   Console.WriteLine("You have to make a bet.");
}

最好不要在这里使用 exceptions(用于 exceptional 行为),但是 TryParse:

  Console.WriteLine("Please, make a bet");

  // keep asking user while
  //  1. bet is not a valid floating point
  //  2. bet is negative
  //  3. bet is too high 
  while (!double.TryParse(Console.ReadLine(), out bet) || bet < 0 || bet > 1e100) {
    Console.WriteLine("You have to make a bet.");
  }

  // from now on bet is a valid double value in [0..1e100] range