'C# - how to catch input exception and continue program to run - BMI calculator

I have a BMI calculator code, however I need to handle exceptions somehow. By exception I mean different input format than expected (example - user is asked to input his weight in kg and he puts letters instead). In this case program should throw error msg "Please give correct weight in kg" and continue to run (ask about height, throw exception if height is not correct, calculate bmi, etc.) How to handle using try catch or parse? How to define variables in such cases?

namespace BMI
{
class Program
{
    static void Main(string[] args)
    {            
        Console.Write("Give your weight in kg: ");
        double weight= Convert.ToDouble(Console.ReadLine());

        Console.Write("Give your height in m: ");
        double height= Convert.ToDouble(Console.ReadLine());

        double BMI = (weight/ (height * height));
        Console.WriteLine("Your BMI is: " + Math.Round(BMI, 2));

        if (BMI < 16)
            Console.WriteLine("text");
        else
            if (BMI < 18.5)
            Console.WriteLine("text text");
        else
            if (BMI < 25)
            Console.WriteLine("text text text");
        else
            if (BMI > 25)
            Console.WriteLine("text text text");

        Console.ReadKey();
    
    }  
        
        
 }

}



Solution 1:[1]

One way of doing this would be double.TryParse(). This returns a boolean if the string is able to be parsed into a double variable.

Here is a example of how you do it:

double outputVariable;
if(!double.TryParse(Console.ReadLine(), out outputVariable))
{
    Console.WriteLine("The Input is unable to be parsed");
}
else
    Console.WriteLine($"The output {outputVariable} is a double");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ZwiebelTVDE