【问题标题】:Exception Using If Else使用 If Else 的异常
【发布时间】:2018-02-13 01:15:13
【问题描述】:

我的任务是计算售价和成本价值。 我不知道有什么想法可以为异常编写一个好的编码。

Private Sub ButtonCalculate_Click(sender As Object, e As EventArgs) Handles ButtonCalculate.Click
    Dim SellingPrice As Double
    Dim CostValue As Double
    Dim Commission As Double
    Dim CommissionRate As Double = 0.2

    If Me.TextBoxSellingPrice.Text <> "" Or Me.TextBoxCostValue.Text <> "" Then

        Try
            SellingPrice = Double.Parse(TextBoxSellingPrice.Text)
            CostValue = Double.Parse(TextBoxCostValue.Text)

            'Calculation
            Commission = CommissionRate * (SellingPrice - CostValue)

            'Display
            Me.TextBoxDisplay.Text = Me.TextBoxName.Text
            Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")
        Catch
            MessageBox.Show("Wrong Input", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    Else
        MessageBox.Show("Please fill your data completely", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End If

End Sub

输出: Figure 1

【问题讨论】:

  • coding for exceptional 是指异常处理吗?如果你使用Double.TryParse(),你真的不需要异常处理程序
  • 正如@Plutonix 建议的那样,您通常不应该尝试捕获一开始就可以避免的异常。在使用它之前验证用户输入,然后不能抛出异常。 TryParse方法一步完成验证和转换。
  • 我的意思是Else MessageBox.Show("Please fill your data completely", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information) 可以使用 if else 概念来处理这个异常吗?
  • 外部检查不是异常处理——它是@jmcilhinney 提到的数据验证。如果它失败,你也可以只使用Return,所以如果你使用TryParse,你就没有 else 或异常处理程序 - 更简单
  • 这里没有必要区分空白字段和​​包含“Hello World”的字段。两者都不能转换为数字,因此两者都是错误的。调用TryParse 会将文本转换为有效的数字,如果无效则毫无例外地告诉您。您有两个经验丰富的开发人员告诉您在这里使用TryParse。您可能应该调查一下。

标签: vb.net


【解决方案1】:

使用异常处理来检查数据是否正确并不是最佳实践。首先,与仅使用 If..Then..Endif 相比,Try..Catch 块的性能非常差,因为在后台发生了相当多的事情,但有例外。在您的情况下,它不会产生重大影响,但如果 Try..Catch..End Try 处于循环中,您的程序可能会受到相当大的性能影响。

除了编写一些 If..End If 语句来验证您的输入数据之外,别无他法。正如其他评论者所说,使用 .TryParse 是一种很好的开始方式..

If Not Double.TryParse(TextBoxSellingPrice.Text, SellingPrice) Or Not Double.TryParse(TextBoxCostValue.Text, CostValue) Then
    MessageBox.Show("Invalid input. Please enter positive numbers only")
    Exit Sub
End If
If SellingPrice < CostValue Then
    MessageBox.Show("Selling Price must be greater than cost")
    Exit Sub
End If
If Not SellingPrice > 0 Or Not CostValue > 0 Then
    MessageBox.Show("Selling price and cost must be >0")
    Exit Sub
End If
'Calculation
Commission = CommissionRate * (SellingPrice - CostValue)
'Display
Me.TextBoxDisplay.Text = Me.TextBoxName.Text
Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")

你也可以看看ErrorProvider component

【讨论】:

  • Nit:拥有Try/Catch 块几乎没有成本。当有一个和/或玩 StackTrace 时,成本就来了。这里有几个 MSIL 类型的帖子和其他 Summary answers。也就是说,当有更主动的测试方法(例如TryParse)时,将它们用于程序流程
  • 我得到了信息,它对我很有帮助。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多