Convert.ToDouble 引发 FormatException
Convert.ToDouble raises a FormatException
如何跳过“System.FormatException”?
示例:
public void HowMuchBookCar()
{
Console.Write("\nOk, how much Euros you want to book in 'CarAndBeauty': ");
double howMuch = Convert.ToDouble(Console.ReadLine());
CarAndBeauty = Input(CarAndBeauty, howMuch);
Save(@"C:\Users\tobia\Desktop\Neuer Ordner\JanuaryCategorie.txt");
Console.Clear();
WannaBook();
}
此方法是在“汽车与美容”类别中预订特定金额。
如果用户在这里键入例如“G”(或不适用于此变量的内容),它会抛出“System.FormatException”并且程序停止工作...
这很有道理……但是我怎样才能防止抛出异常而不是抛出特定代码呢?
(例如:“请输入有效信息!”)
要避免 FormatException
,请改用 double.TryParse。
您可以这样做:
double result;
while (true) // until user has typed something correct
{
Console.WriteLine("Input a number:");
var line = Console.ReadLine();
// NOTE: optionally here, you may want to exit program if say, user has typed 'exit'
if (double.TryParse(line, out result))
break;
Console.WriteLine("Input was not recognized");
}
Console.WriteLine($"You typed: {result:G}");
如何跳过“System.FormatException”?
示例:
public void HowMuchBookCar()
{
Console.Write("\nOk, how much Euros you want to book in 'CarAndBeauty': ");
double howMuch = Convert.ToDouble(Console.ReadLine());
CarAndBeauty = Input(CarAndBeauty, howMuch);
Save(@"C:\Users\tobia\Desktop\Neuer Ordner\JanuaryCategorie.txt");
Console.Clear();
WannaBook();
}
此方法是在“汽车与美容”类别中预订特定金额。 如果用户在这里键入例如“G”(或不适用于此变量的内容),它会抛出“System.FormatException”并且程序停止工作...
这很有道理……但是我怎样才能防止抛出异常而不是抛出特定代码呢? (例如:“请输入有效信息!”)
要避免 FormatException
,请改用 double.TryParse。
您可以这样做:
double result;
while (true) // until user has typed something correct
{
Console.WriteLine("Input a number:");
var line = Console.ReadLine();
// NOTE: optionally here, you may want to exit program if say, user has typed 'exit'
if (double.TryParse(line, out result))
break;
Console.WriteLine("Input was not recognized");
}
Console.WriteLine($"You typed: {result:G}");