Title: How to handle exception when wrong user input type
Tags: c#
Question: I would like to know how to edit the following code to make users enter a number if they enter a string for any of the following prompts.
Console.Write(&quot;\nPlease enter a number: &quot;);
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(&quot;\nPlease enter a operator:  &quot;);
string optr = Console.ReadLine();
Console.Write(&quot;Please enter a number: &quot;);
double num2 = Convert.ToDouble(Console.ReadLine());
double total;
string end;
do
{
switch (optr)
{
case &quot;+&quot;:
total = (num1 + num2);
Console.Write(&quot;Total : &quot; + total);
break;
Console.Write(&quot;Invalid operator&quot;);
break;
}
Console.WriteLine(&quot;\n \nDo you want to make another calculation? Yes or No: &quot;);
end = Console.ReadLine();
} while (end != &quot;No&quot;);
Console.Write(&quot;Press Enter key to exit&quot;);
Console.ReadKey();
Comment: Does this answer your question? [How can I check if a string is a number?](https://stackoverflow.com/questions/6733652/how-can-i-check-if-a-string-is-a-number)

Comment: As a rule of thumb, exceptions should be used for unexpected or exceptional events, like failing to write to disk. Having the user enter something incorrectly is probably an expected event, so it is better to check that the operation is valid before attempting it, i.e. see `Double.TryParse`


Here is another answer: Rather than handling the exception, I would store the Console.ReadLine() in a string for both of the numbers, then test to see if they convert to a Double. If they do, move on, if they don't, show an error and ask the user to try again.
Double.TryParse will allow you to attempt to convert from String to Double and will never throw an exception.
https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-5.0#System_Double_TryParse_System_String_System_Double__

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:05/07/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#>', 'Title': 'How to handle exception when wrong user input type', 'ViewCount': 156, 'id': 67428235, 'user_AboutMe': None, 'user_AccountId': 17816639.0, 'user_DisplayName': 'bryan tran', 'user_Reputation': 1.0, 'user_Views': 1.0, 'user_id': 12940070.0}}