我如何处理vb.net中的转换错误

时间:2011-09-12 00:24:54

标签: vb.net casting error-handling

我想抓住System.InvalidCastException错误。如果我在计算器中输入一个数字,程序运行正常。如果按下计算按钮时文本框中没有任何内容,则会出现投射错误Conversion from string "" to type 'Decimal' is not valid.我理解为什么会出现错误。我不知道该怎么办。我希望程序转储空数据并返回等待用户的输入。感谢

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
  Dim FedTaxRate = 0.13     ' constants for taxes and work week
  Dim StateTaxRate = 0.07
  Dim StandWorkWeek = 40
  Dim GrossPay As Decimal    ' variables
  Dim NetPay As Decimal


  If txtInWage.Text = "" Then
      MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
  End If


  If txtInHours.Text = "" Then
      MessageBox.Show("Please enter a number in the hours box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
  End If

  Dim decInHours = CDec(txtInHours.Text) 'converts text boxes to numerical data
  Dim decInWage = CDec(txtInWage.Text)


  If decInHours <= StandWorkWeek Then        'calculates gross and net pay as well as taxes. Also includes overtime after 40 hours
    GrossPay = (decInHours * decInWage)
  ElseIf decInHours > StandWorkWeek Then
    GrossPay = (decInWage * StandWorkWeek) + (decInHours - StandWorkWeek) * (decInWage * 1.5)
  End If

  NetPay = GrossPay - (GrossPay * FedTaxRate) - (GrossPay * StateTaxRate)

  lblGrossPay.Text = GrossPay.ToString("c")
  lblNetPay.Text = NetPay.ToString("c")
  lblFedTax.Text = (GrossPay * FedTaxRate).ToString("c")
  lblStateTax.Text = (GrossPay * StateTaxRate).ToString("C")


End Sub

2 个答案:

答案 0 :(得分:1)

你可以做到

If txtInWage.Text = "" Then
    MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
    exit sub
End If

答案 1 :(得分:1)

如果您从TextBox获得输入,则用户可能会输入字母,在这种情况下CDec也会失败。

您可以改用Decimal.TryParse

Dim decInHours As Decimal
Dim decInWage As Decimal    
If Not Decimal.TryParse(txtInHours.Text, decInHours) Then
        MessageBox.Show("Please enter a number in the hours box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        Exit Sub ' As in answer from Fredou.
End If

If Not Decimal.TryParse(txtInWage.Text, decInWage) Then
        MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        Exit Sub ' As in answer from Fredou.
End If