【问题标题】:Make Exceptions work [closed]使例外工作[关闭]
【发布时间】:2014-10-30 05:56:25
【问题描述】:

我不确定如何让异常起作用

程序应提示输入要转换的英镑整数和汇率。然后它应该以类似于下面的输出的方式显示等量的 follar 数。

这里的第一部分是我的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CurrencyConvertor
{
  class Program
  {
    static void Main(string[] args)
    {
      CurrencyConvertor();
      Console.ReadLine();
    }

    private static void CurrencyConvertor()
    {
      int ivalue;
      float exchange;
      float results;
      bool valid;

      Console.WriteLine(" please enter a whole number of pounds");

      do
      {
        try
        {
           ivalue = int.Parse(Console.ReadLine());
           Console.WriteLine(" pounds entered : " + ivalue);

           Console.WriteLine("please enter the exchange rate");
           exchange = float.Parse(Console.ReadLine());
           Console.WriteLine(" exchange rate is " + exchange);

           results = ivalue * exchange;
           Console.WriteLine(" £ " + ivalue + " is equivlent to" + " $ {0:N}", results);
           valid = true;
        }
        catch
        {
          Console.WriteLine("unable to convert to integer");
          Console.WriteLine(" Try again- ensure you enter a number");
          valid = false;
        }
      } while (valid == false);
      Console.ReadLine();
    }
  }
}

应验证两个输入以确保用户输入适当的数据类型 - 下面的输出说明了用户输入非数字数据时的预期输出。

所以它应该显示

please enter an integer
try again - ensure you enter an integer
12
pounds entered 12
please enter an exchange rate 
asd
unable to convert to a number 
try again - ensure you enter a number
1.56
exchange rate is 1:56
£12.00 is equivalent to $18.72

我似乎无法让它显示汇率错误消息“无法转换为数字”

【问题讨论】:

  • 你试过调试你的代码吗?哪条线似乎失败了?
  • 请去掉所有空行
  • 那里应该有另一个异常,所以它应该显示 'console.writelinne("unable to conver to a number")' @YuvalItzchakov 不确定它的去向?
  • 您以完全错误的方式使用异常,您应该使用int.TryParse 来验证数字,而不是捕获异常

标签: c# exception


【解决方案1】:

你的代码有一些缺陷:

  • 您应该更喜欢 int.TryParse 而不是 ParseException 应该是一种意外行为,您必须以某种方式做出反应。用户输入并不意外,您知道用户有可能输入您可以/必须验证的无效数据。

  • 当你使用异常时,你不应该一次捕获所有异常,而是你知道如何反应的某种类型的异常。 int.Parse 本身会抛出三种异常(参见http://msdn.microsoft.com/de-de/library/b3h1hf19(v=vs.110).aspx),您可以从系统本身获取其他一些异常。您的代码应该捕获 FormatException 而不是包罗万象。

  • 无论如何,如果您只是想修复您的代码,您可以使用两个单独的 try .. catch 块和单独的错误消息来解决您的问题。

【讨论】:

    【解决方案2】:

    例外是为了捕捉例外——你不希望发生但可能发生的事情

    您应该改用TryParse 方法

    while(!int.TryParse(Console.ReadLine(), out ivalue)
    {
        Console.WriteLine("Thats not a number, try again");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-27
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多