how can i skip a "System.FormatException" ?
Example:
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();
}
This method is to book a specific amount into the categorie "Car & Beauty". If the user would type here for example "G" (or something that does not work with this variable) it throws "System.FormatException" and the program stop working...
That makes sense ... but how can I prevent the exception from being thrown and instead a specific code? (for example: "please make valid entry!")
To avoid FormatException
, instead, use double.TryParse.
Here's how you could do it:
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}");