Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

How to properly do Exception Handling with try and catch using C#

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);
            }
        }
question from:https://stackoverflow.com/questions/65599105/how-to-properly-do-exception-handling-with-try-and-catch-using-c-sharp

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

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...