试试 Catch C# 我该怎么做? [英] Try Catch C# How Do I do it?

查看:25
本文介绍了试试 Catch C# 我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一项任务,现在我必须实施 Try &Catch-method 也可以在我的程序中捕获数字以外的输入.我了解我的学习书中的过程和解释,并且在尝试时也做了一些小例子.但是当我想在我的作业中实现这一点时,我陷入了困境.有人可以在庄园里向我解释一下,不要破坏任何东西,而是一路帮助我吗?

im working on a assignment where I now have to implement the Try & Catch-method too catch inputs other than numbers in my program. I understand the process and explanations in my study-book and have also done some minor examples while trying it out. But when I want to implement this into my assignment I am getting stuck. Can someone please explain to me in a manor as to not spoil anything but try and help me along the way?

这是我的代码:

using System;

namespace BastunKP
{
  class Program
  {
       public static double FahrToCels(double fahr)
       {
          return (fahr - 32) * 5 / 9;
       }

       public static void Main(string[] args)
       {
          Console.WriteLine("Skriv in Fahrenheit: ");
          double fahr = Convert.ToDouble(Console.ReadLine());
          double tempCels = FahrToCels(fahr);

          do            
          {      
            try               
            {
                //Dont know what to write here.
            }
            catch
            {
                Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
            }

            if (tempCels < 73)
            {
                Console.WriteLine("Temperaturen är för kallt, skruva upp lite!");
            }
            else if (tempCels > 77)
            {
                Console.WriteLine("Temperaturen är för varmt, skruva ner lite!");
            }
            else 
            {
                Console.WriteLine("Temperaturen är nu bra, hoppa in!");
                Console.ReadKey();
            }

            fahr = Convert.ToDouble(Console.ReadLine());
            tempCels = FahrToCels(fahr);              
          }        
          while (tempCels < 73 || tempCels > 77);
          return;
      }
   }
}

推荐答案

首先,让我们编写没有任何异常处理的代码.先把基础打好.我们需要一个方法:

First of all, lets write code without any exception handling. Get the basics right first. We need a method that:

  1. 向用户询问华氏温度.
  2. 如果输入不是有效的double,请转到1.
  3. 将值转换为摄氏度.
  4. 如果没有,请转到 1.
  5. 如果摄氏温度不属于(73, 77),则转1.

  1. Asks the user for a temperature in Fahrenheit.
  2. If the input is not a valid double, go to 1.
  3. Convert the value to Celsius.
  4. If not, go to 1.
  5. If the temperature in Celsius does not belong to (73, 77) go to 1.

public static double GetTemperatureFromUser()
{
     while (true)
     {
          Console.Write("Enter temperature in Fahrenheit: ");
          var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));

          if (t < 73)
          {
              Console.Write("Temperature is too low. Try again.");
          }
          else if (t > 77)
          {
              Console.Write("Temperature is too high. Try again.");
          }
          else
          {
              return t;
          }
     }
}

好的,看起来不错.现在让我们添加一些异常处理.第一个问题:这里会出现什么问题并抛出异常?

Ok, that looks good. Now let's add some exception handling. First question: what can go wrong here and throw an exception?

var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));

似乎是一个嫌疑犯.还有什么可以扔的吗?嗯,没有.

seems like a likely suspect. Is there anything else that can throw? Hmmm, no.

好的,第二个问题:如果 ToDouble() 抛出什么代码不应该执行?好吧,显然任何取决于 ToDouble() 的结果.所以所有这些代码也都在 try 块中.

Ok, second question: what code shouldn't be executing if ToDouble() throws? Well, anything that depends on the result of ToDouble() obviously. So all that code also goes in the try block.

好的,第三个问题:如果 ToDouble() 抛出,应该运行什么代码?在我们的例子中,我们应该通知用户输入不是有效的double.好的,该代码需要进入 catch 块.

Ok, third question: what code should run if ToDouble() throws? In our case we should inform the user that the input was not a valid double. Ok, that code needs to go in catch block.

try-catch 想象成一个控制代码执行路径的花哨的 if:如果代码抛出,转到 catch如果没有,继续在 try 块内正常执行.

Think of try-catch as a fancy if that controls the execution path of your code: if the code throws, go to catch if not, keep executing normally inside the try block.

第四个问题:无论发生什么,在 trycatch 块中的其他所有内容之后应该运行什么代码?在你的情况下什么都没有,但如果有,它会进入 finally 块.

Fourth question: what code should run after everything else inside the try or catch blocks no matter what happens? In your case nothing, but if there were, it would go in the finally block.

请注意,catchfinally 块不是强制性的.唯一的规则是它们中的至少一个必须紧跟在 try 块之后;try-catchtry-finallytry-catch-finally 都是有效的.

Note that catch and finally blocks are not mandatory. The only rule is that at least one of them must be present immediately following a try block; try-catch, try-finally and try-catch-finally are all valid.

第五个也是最后一个:你想处理什么异常?您应该始终只处理您知道如何处理的异常,而忽略所有其他异常.ToDouble 可以抛出哪些异常?如果您阅读文档,您会看到它可以抛出 FormatExceptionOverflowException.您可以同时处理这两种情况,因为它们等同于:和无效的用户输入.

Fifth and last: what exceptions do you want to handle? You should always handle only the exceptions that you know how to handle and ignore all others. What exceptions can ToDouble throw? If you read the documentation you'll see it can throw FormatException and OverflowException. You can handle both because they amount to the same thing: and invalid user input.

好的,让我们重写我们的方法:

Ok, lets rewrite our method:

while 循环是否依赖于 ToDouble 中发生的任何事情?不,无论内部发生什么,该方法都应该在循环中运行;退出循环的唯一方法是当用户输入有效数字并且方法返回时.好的,while 块超出了任何异常处理的范围,用户提示也是如此:

Does the while loop depend on whatever happens in ToDouble? No, the method should be running in a loop no matter what happens inside; the only way to exit the loop is when the user inputs a valid number and the method returns. Ok then, the while block goes outside any exception handling and so does the user prompt:

public static double GetTemperatureFromUser()
{
     while (true)
     {
         Console.Write("Enter temperature in Fahrenheit: ");
         //...
     }
}

现在下一条指令是我们的主要嫌疑人,所以它显然必须在 try 块中.我们在方法中编写的其他所有内容都取决于 t 的值,因此我们将所有内容也放在 try 块中:

And now the next instruction is our primary suspect, so it obviously must go inside the try block. Everything else we've written in our method depends on the value of t so we put all that also inside the try block:

public static double GetTemperatureFromUser()
{
     while (true)
     {
          Console.Write("Enter temperature in Fahrenheit: ");

          try
          {
              var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));

              if (t < 73)
              {
                  Console.Write("Temperature is too low. Try again.");
              }
              else if (t > 77)
              {
                  Console.Write("Temperature is too high. Try again.");
              }
              else
              {
                  return t;
              }
         }
     }
} 

好的,现在我们只缺少 catch 块.我们将为我们知道如何处理的每个异常添加一个:

Ok, now we're only missing the catch block. We'll add one for each exception we know how to handle:

public static double GetTemperatureFromUser()
{
     while (true)
     {
          Console.Write("Enter temperature in Fahrenheit: ");

          try
          {
              var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));

              if (t < 73)
              {
                  Console.Write("Temperature is too low. Try again.");
              }
              else if (t > 77)
              {
                  Console.Write("Temperature is too high. Try again.");
              }
              else
              {
                  return t;
              }
         }
         catch (FormatException)
         {
              Console.Write("Invalid number format. Try again.");
         }
         catch (OverflowException)
         {
              Console.Write("Number is too large or too small. Try again.");
         }
     }
} 

好了,我们完成了.

这篇关于试试 Catch C# 我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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