Sollo
Sollo

Reputation: 163

Conversion String to Double is not valid in VB

I have a problem with try and catch in VB. I have 2 buttons(btnCalculate,btnPay) and 3 labels(lblTotal, lblCash, lblChange)

btnCalculate = total the price
btnPay = amount paid by customer

lblTotal = display the total price
lblCash = display cash paid by customer
lblChange = display the change

EDIT:Conversion from string to type Double is not valid error

Private Sub btnPay_Click(sender As Object, e As EventArgs) Handles btnPay.Click
    Dim payAmount As Double
    Dim total As Double
    total = CDbl(lblTotal.Text)

    Do While (payAmount < total)
        payAmount = Val(InputBox("Enter customer pay amount: "))
        If (payAmount < total) Then
            MessageBox.Show("Please pay the amount of total bill!")
        Else
            lblCash.Text = "$" & CStr(payAmount)
            lblChange.Text = "$" & CStr(payAmount - total)
        End If
    Loop
End Sub

Upvotes: 0

Views: 216

Answers (1)

Heinzi
Heinzi

Reputation: 172220

The problem is that you throw away the real error cause. Look at what your program does:

  • An invalid number is entered: Please enter valid number! is shown.
  • The system is out of memory: Please enter valid number! is shown.
  • You made a programming mistake: Please enter valid number! is shown.
  • Something else went wrong: Please enter valid number! is shown.

That's not good, is it? In fact, you only want to show "Please enter a valid numer" when an invalid number has been entered, so don't do Pokemon exception handling: Put your exception handling around the statement where you expect the error to occur and catch only the specific exception that you need.

If you do global exception handling, include ex.Message in the error message you show to ensure that the real cause of the error can be determined.

Upvotes: 1

Related Questions