This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
The easiest way, IMHO, to change the routine is to rewrite
Parse
into correspondingTryParse
:...
A bit more complex (you have to convert
float
intofloat?
)The same scheme for
CelsiusInput
The underlying mechanic of the code is
TryParse(Console.ReadLine()...
TryParse
returnstrue
) we just return the out (parsed value).TryParse
returnsfalse
) we return some special a value (-1
forUserChoice
ornull
in case ofFahrenheitInput
orCelsiusInput
)P.S. in the first
switch
you have justcase 1
,case 2
andcase 5
; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implementcase 3 and case 4
in theswitch
or edit the error message.You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
While all the answers provided seem to work, the question you asked was
and I just want to point out that you do this by putting the part which throws the
exception
in antry
-catch
-block. What this does is it executes the code withintry
until anexception
is beeing thrown and then passes thisexception
s as a parameter to thecatch
-part where you can handle it:EXAMPLE
Of course preventing
exception
s from beeingthrow
n at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Usingswitch
-case
-statements for error-handling is quite common practice...Use
int.TryParse
instead ofint.Parse
andfloat.tryParse
instead offloat.Parse
TryParse
is your good friend here. In most scenarios, you should favor usingTryParse
thanParse
. In your example, you can do something like:Parse vs. TryParse