Ticherhaz FreePalestine
Ticherhaz FreePalestine

Reputation: 2377

Exception Using If Else

I have a task to make a calculation of selling price and cost value. I don't know have any idea to make a good coding for exception.

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

Output: Figure 1

Upvotes: 0

Views: 347

Answers (1)

David Wilson
David Wilson

Reputation: 4439

Using exception handling to check that data is correct isn't really the best practice. For a start, the performance of Try..Catch blocks is pretty poor compared to just using If..Then..Endif as there is a fair amount of stuff happening in the background with exceptions. In your case it wont make a major difference, but if the Try..Catch..End Try is in a loop, your program can take quite a performance hit.

There is little else to do other than to write some If..End If statements to validate your input data .. As other commenters had stated, using .TryParse is an exellent way to start things off ..

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")

You could also have a look at the ErrorProvider component

Upvotes: 2

Related Questions