带有 Do-While 循环的 Try-Catch [英] Try-Catch with Do-While loop

查看:29
本文介绍了带有 Do-While 循环的 Try-Catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 C# 课程并完成我的第二个任务.我已经能够完成代码.我唯一无法编码的是如何使用以及在哪里使用 Try &抓住.由于我是 C# 新手,我不知道如何编码.

I'm studying a C # course and doing my second task. I've been able to get the code done. The only thing I can´t code is how to use and where to use Try & Catch. Since I'm new to C #, I don´t know how to code it.

我已经搜索了解决方案,但大部分都在 Java 中.

I've searched for solution but most of it is within Java.

任务是一个美国人应该进入桑拿房,而桑拿房只显示摄氏温度.您输入华氏度,它会转换为摄氏度.桑拿的温度为 73-77C.

The task is that an American should enter the sauna and the sauna shows only Celsius degrees. You enter Fahrenheit degrees and it converts to Celsius degrees. Degrees for okey warmth of the sauna are 73-77C degrees.

这是我的代码:

public static int FahrToCel(int fahr)
    {
        int cel = (fahr - 32) * 5 / 9;
        return cel;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Skriv in Fahrenheit: ");
        int fahrenheit = int.Parse(Console.ReadLine());
        //Användaren skriver in ett värde som lagras i fahrenheit
        int celsius = FahrToCel(fahrenheit);
        /* I celsius finns nu antal grader omvandlat från fahrenheit till celsius. */

        /*Här får lowerTempLimit värdet 77 
         * &  upperTempLimit = 77 */
        int lowerTempLimit = 73;
        int upperTempLimit = 77;

        /* While-do loop som breaker efter en iteration.
        *If satserna skriver utvärmen i bastun och säger till om temperatur ska sänkas eller höjas beroende på temperaturn i celsius. 
        * Om temperaturn är mellan 73 - 77 grader, så har bastun godtyckligt bra temperatur */
        do
        {
            if (celsius < lowerTempLimit)
            {
                Console.WriteLine("Bastun är inte tillräckligt varmt. Värme i bastun {0}, skruva upp värmen", celsius);
            }
            else if (celsius > upperTempLimit)
            {
                Console.WriteLine("Bastun är för varmt. Värme i bastun {0}, skruva ner värmen", celsius);
            }
            else
            {
                Console.WriteLine("Bastun är tillräckligt varmt för att kunna basta. Värme i bastun {0}", celsius);
            }
        }
        while (celsius < lowerTempLimit || celsius > upperTempLimit);

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey();
    }

推荐答案

Main 是顶层方法;它仅由操作系统调用.通常,顶级方法应该具有某种形式的异常处理.否则,您的代码中发生的任何异常都会传播到操作系统本身,而这通常不会产生最友好的用户界面.

Main is a top-level method; it is called only by the operating system. In general, top level methods should have some form of exception handling. Otherwise, any exception that occurs in your code will propagate to the operating system itself, and that usually doesn't result in the most friendly UI.

向控制台应用程序添加顶级异常处理相对容易.

To add top level exception handling to a console application is relatively easy.

public static void Main(string[] args)
{
    try
    {
        //Put all of your code here
    }
    catch (System.Exception ex)
    {
        Console.WriteLine("A problem has occurred and the application will now exit. Details: {0}", ex.Message);
    }
}

这是你能做的最基本的事情.您还可以考虑写入事件日志或应用程序调试日志,或者在用户可能能够理解的情况下提供其他信息.

That's the most basic thing you can do. You might also consider writing to the event log or an application debug log, or providing additional information if the user is likely to be able to understand it.

此外,在某些情况下,您的代码可能会抛出异常,而您想要处理它,即不仅仅是退出应用程序.在这些情况下,您还应该使用 try 块包装特定的风险区域.

In addition, there may be cases where your code will throw an exception and you want to handle it, i.e. not just exit the application. In those cases, you should wrap the specific area of risk with a try block as well.

现在在您的情况下,实际上很少有代码可以引发异常(除了灾难性的事情,例如 O/S 内存不足或类似的情况).唯一的一行真的是

Now in your case, there is actually very little code that could throw an exception (other than something catastrophic, such as the O/S running out of memory or something like that). The only line really is

 int fahrenheit = int.Parse(Console.ReadLine());

你可以做到

 //Don't do this
 while (true)
 {
     try
     {
         int fahrenheit = int.Parse(Console.ReadLine());
         break;
     }
     catch (FormatException ex)
     {
         Console.WriteLine("Nummer nicht gut!!!")
     }
}

但是您可以轻松地将其替换为对 TryParse 的调用,这将避免出现异常的可能性.这比将 Parse 包装在它自己的 try 块中更好.try 块在这里会显得过分,并且在可能是常见用例的情况下会降低性能(用户不小心输入了非数字字符串).

But you could easily replace that with a call to TryParse which would avoid the possibility of exception. That would be a better practice than wrapping Parse in its own try block; a try block would be overkill here and would hurt performance in what is probably a common use case (user accidentally enters a non-numeric string).

 int fahrenheit;
 while (true)
 {
     if (int.TryParse(Console.ReadLine(), out fahrenheit)) break;
     Console.WriteLine("Achtung!  Nummer kaput!");
 }

如果您决定使用 try/catch 而不是 TryParse,请注意捕获 FormatException 比捕获 System.Exception 更好,因为您只需要想处理格式异常.另请参阅 为什么 catch(例外) 不好.

If you do decide to use try/catch instead of TryParse, note that it is a better idea to catch FormatException than to catch System.Exception, since you only want to handle the format exception. See also Why catch(Exception) is bad.

这篇关于带有 Do-While 循环的 Try-Catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆