使用If Else的例外情况

时间:2018-02-13 01:15:14

标签: vb.net

我的任务是计算销售价格和成本价值。 我不知道有什么想法为异常做好编码。

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

1 个答案:

答案 0 :(得分:2)

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

除了编写一些If..End If语句来验证您的输入数据之外别无他法。正如其他评论者所述,使用.TryParse是一种优秀的方式来启动... < / p>

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