【问题标题】:try/catch within decimal method c#在十进制方法c#中尝试/捕获
【发布时间】:2016-05-16 04:16:46
【问题描述】:

首先,这是我正在处理的任务,但这不是它的要求,只是我希望使用的东西。我正在尝试将 try/catch 语句与我的十进制方法一起使用。

    private decimal NewCar()
    {
        decimal newCar = 0.00m;

        try
        {
            newCar = decimal.Parse(vehicleTextBox.Text);
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid entry (Format Exception). \n" + "Please enter a valid decimal number.");
            Keyboard.Focus(vehicleTextBox);
            vehicleTextBox.SelectAll();
            return;
        }
        catch (Exception)
        {
            MessageBox.Show("Invalid entry (General Exception). \n" + "Please enter a valid decimal number.");
            Keyboard.Focus(vehicleTextBox);
            vehicleTextBox.SelectAll();
            return;
        }

        if (newCar < 0)
        {
            MessageBox.Show("Invalid entry (Negative Value). \n" + "Please enter a valid decimal number.");
            Keyboard.Focus(vehicleTextBox);
            vehicleTextBox.SelectAll();
            return;
        }

        return newCar;
    }

我收到一条错误消息,提示“需要一个可转换为'十进制'的类型的对象”,但如果我将 newCar 变量放在那里,或者删除 try/catch 中的返回语句,我会收到太多消息框它不会停止计算。我需要这是一种十进制方法,以便在其他计算中使用。

任何帮助表示赞赏。

【问题讨论】:

  • 不要使用 try catch 来判断它是否是一个有效的输入。一般来说,这不是好的做法。改用 Decimal.TryParse ..
  • 您在哪个事件中调用了 newcar 方法?你能不能也显示那个代码。而且你不能使用 return 语句从具有某种返回类型的方法返回,该语句不返回任何内容。
  • 我无法让它按照我想要的方式工作,并决定在我的calculate_button 方法中使用try-catch,并在用于计算的不同方法中引用了decimal.Parse(vehicleTextBox.Text)。现在一切似乎都很好,谢谢大家的回答!

标签: c# methods try-catch


【解决方案1】:

你说过你的方法会返回一个小数。所以你必须返回一个小数。你不能只写return,因为这表明你什么都没有返回。

现在,您可能应该将错误处理移出方法,并简单地允许异常冒泡。由于您的方法正在解析汽车值(顺便说一句,您的方法名称应该表明,NewCar 表示它正在创建一个新的汽车对象),它不一定与用户交互。它的唯一目的应该是解析文本并给你一个小数。

所以你有两个选择:

  1. 您的方法返回一个错误代码(例如,-1),以便您可以返回一个合适的值。另一种选择是创建一个包装类,用于存储“成功”标志、数据和可能的异常。
  2. 让异常简单地冒泡。

【讨论】:

  • 我确实在方法之外进行了错误处理,所以这对我来说很有意义,我只是想看看是否有办法让它工作,所以我会尝试@Saeed Jahed 下面提到的TryParse 方法
【解决方案2】:

为了补充 Rob 的正确和出色的答案,我还建议使用 TryParse(...) 来捕获异常。

private void NewCar() {
    decimal newCarValue;

    if (decimal.TryParse(vehicleTextBox.Text, out newCarValue))
    {
        // valid decimal.
        // now validate the value of decmial
        if (newCarValue >= 0)
        {
            // All good.  Do the work with car here.
        }
        else
        {
            // complain
        }
    }
    else
    {
        // complain
    }
}

在您的情况下,您正在赶上 Exception 类,这是一个坏主意。假设您的代码有错误,并在创建汽车时导致NullReferenceException。你会告诉用户他们输入了一个无效的值,而实际上这只是代码中的一个被掩埋的错误。

【讨论】:

  • TryParse 方法需要在 newCarValue 变量上使用 out 关键字,因为它是一个输出参数。
【解决方案3】:

确实编译器会抱怨,因为除了最后一个之外,您的所有 return 语句都不正确,您没有返回小数。我建议您在此方法之外采用 MessageBoxes 的逻辑。 如果您想检查数字是否正确转换,我建议您使用 TryParse 方法:

private void TheFunctionThatWasUsingNewCar() {

    decimal newCar;
    //send the uninitialized newCar variable to TryParse. If everything went ok, the variable will contain the equivalente decimal value.
    if(! Decimal.TryParse(vehicleTextBox.Text, out newCar)){
        //You can be almost certain that if the conversion failed it's because of the format
        MessageBox.Show("Invalid entry (Format Exception). \n" + "Please enter a valid decimal number.");
        KeyBoard.Focus(vehicleTextBox);
        vehicleTextBox.SelectAll();
    }
    //Validate the converted number was not negative
    if(newCar < 0){
        MessageBox.Show("Invalid entry (Negative Value). \n" + "Please enter a valid decimal number.");
        KeyBoard.Focus(vehicleTextBox);
        vehicleTextBox.SelectAll();
    }

    //At this point you have your newCar variable and it's valid.
}

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多