How to handle Unhandled exceptions in c# using TryParse

138 Views Asked by At
if (response.ToLower() == "addition") 
{
Console.Write("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
double num2 = double.Parse(Console.ReadLine());
double addition = (num1) + (num2);
Console.WriteLine("The answer is {0}", addition);
if(!double.TryParse (num1, out addition))
     {
      Console.WriteLine("Try Again");
      tryAgain = true;   
     } 
I tried to use try parse to handle my unhandled exception and make the user go back and do it again if they dont input a number/ integer/ decimal. I am new to try parse and dont know how to use it properly, So i would like to ask for a way in which i could handle exceptions in the future as well

Here's an inline link to replit(https://replit.com/@NitikPaudel/Maths-Calculator-Upgraded#main.cs)

2

There are 2 best solutions below

1
JBatz On

I'd try something like below:

    if (response.ToLower() == "addition") 
    {
    double num1;
    double num2;
    Console.Write("Enter a number: ");
    if(!double.TryParse(Console.ReadLine().ToString(),num1)){
       Console.WriteLine("Try Again");
          tryAgain = true;
    };

    Console.Write("Enter another number: ");
    if(!double.TryParse(Console.ReadLine().ToString(),num2)){
       Console.WriteLine("Try Again");
          tryAgain = true;
    };

    double addition = (num1) + (num2);
    Console.WriteLine("The answer is {0}", addition);
}

Or if you would prefer a try/catch

if (response.ToLower() == "addition") 
{
    try{
        Console.Write("Enter a number: ");
        double num1 = double.Parse(Console.ReadLine());
        Console.Write("Enter another number: ");
        double num2 = double.Parse(Console.ReadLine());
        double addition = (num1) + (num2);
        Console.WriteLine("The answer is {0}", addition);
    }
    catch(Exception e){
        Console.WriteLine("Try Again");
        tryAgain = true;
    }
}
0
Demian On

The function TryParse is here to check if a value can be converted and to prevent the exception before it is thrown.

To handle exceptions, you can use try catch, example:

try {
    // do the work
}
catch (Exception ex) {
    // work with exception
}

View this documentation: https://www.tutorialsteacher.com/csharp/csharp-exception-handling