Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to include an exception handling in to this small sample of code. When I am prompted to input the conversionType, I tried to input strings which are supposed to trigger the catch code and print out the error message, but instead the code just shuts down like any other errors, suggesting that the error was not caught by the try catch blocks. I am still learning how exception handling works in C#. So is there anyway to correctly catch the exception and prevent the code from crashing?

static void Main(string[] args)
        {
            int conversionType;
            double number;
            Console.WriteLine("Choose the type of conversion:
" +
                              "1.Celsius to Fahrenheit
" +
                              "2.Fahrenheit to Celsius");

            try
            {
                conversionType = Convert.ToInt32(Console.ReadLine());
                if (conversionType == 1)
                {
                    Console.WriteLine("Enter the Temperature in Celsius: ");
                    number = Convert.ToDouble(Console.ReadLine());
                    number = number * 9 / 5 + 32;
                    Console.WriteLine("Temperature in Fahrenheit: {0:00.0}°F", number);
                }
                else if (conversionType == 2)
                {
                    Console.WriteLine("Enter the Temperature in Fahrenheit: ");
                    number = Convert.ToDouble(Console.ReadLine());
                    number = (number - 32) * 5 / 9;
                    Console.WriteLine("Temperature in Celsius: {0:00.0}°C", number);
                }
            }

            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

You shouldn't use exceptions for this, you have functions like int.TryParse and double.TryParse that return a boolean signifying whether or not they succeeded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...