Try Catch C# How Do I do it?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-15 12:05:02

问题


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?

Here is my code:

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;
      }
   }
}

回答1:


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

  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.

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.

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.

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.

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.

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.

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:

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: ");
         //...
     }
}

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;
              }
         }
     }
} 

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.");
         }
     }
} 

And there you go, we're done.




回答2:


There is no required try/catch to check valid input. You could use double.TryParse;

Console.WriteLine("Skriv in Fahrenheit: ");
double fahr;
double tempCels;
bool isInputCorrect = false;
while (!isInputCorrect)
{
    var input = Console.ReadLine();
    if (!double.TryParse(input, out fahr))
    {
        Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
        continue;
    }
    tempCels = FahrToCels(fahr);
    if (tempCels < 73)
    {
        Console.WriteLine("Temperaturen är för kallt, skruva upp lite!");
        continue;
    }
    else if (tempCels > 77)
    {
        Console.WriteLine("Temperaturen är för varmt, skruva ner lite!");
        continue;
    }
    isInputCorrect = true;
}
Console.WriteLine("Temperaturen är nu bra, hoppa in! tempCels : " + tempCels);
Console.ReadKey();

If you insist to use try/catch, you could try like this;

Just replace double.TryParse part.

var input = Console.ReadLine();
try
{
    fahr = Convert.ToDouble(input);
}
catch (Exception e)
{
    Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
    continue;
}


来源:https://stackoverflow.com/questions/47991596/try-catch-c-sharp-how-do-i-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!