c# - 当 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)
也不能作为条件工作。那么,当双精度为空/空时,我该如何进行异常处理?
解决方案
抛出异常的行,在这种情况下,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.");
}
推荐阅读
- apex - 单击按钮后如何使用顶点将闪电组件插入到visualforce页面
- c# - Unable to resolve service for type 'System.Net.Http.HttpClient'
- vba - How to assign a recipient to .To?
- sql - PostgreSQL 查询优化 musicbrainz
- c++ - Constructing a std::initializer_list of dynamic size, part II
- kubernetes - Kubernetes YAML/JSON 配置文件文档在哪里?
- drupal - 是否有检索所有当前登录用户的功能?
- jquery - 无法从具有依赖项的 $injector.get() 获取服务实例
- r - R,ggplot:y轴上的小数
- c++ - Simulink“访问冲突”写入 C++ lambda 函数捕获列表中的 PWork 变量