首页 > 解决方案 > 当 C# 中的双精度为 Null/Empty 时如何创建异常?

问题描述

我正在用 C# 创建二十一点。游戏开始时,我的代码要求用户“请打赌”。但是,用户可能只是单击“进入”,应用程序就会崩溃。我试着做一个例外:

  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)也不能作为条件工作。那么,当双精度为空/空时,我该如何进行异常处理?

标签: c#double

解决方案


抛出异常的行,在这种情况下,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.");
}

推荐阅读