【问题标题】:How to catch/handle number format exception in vb.net?如何在 vb.net 中捕获/处理数字格式异常?
【发布时间】:2023-04-11 04:17:01
【问题描述】:

我想在我正在创建的模块上添加“try catch”语句。我想指定以数字格式捕获的异常。这是示例代码,

    Try
       interest = me.txtInterest.text
       principal = me.txtPrincipal.text
       totalPayment = interest + principal
    Catch ex As Exception 'What is the proper exception for Number Format?
        MsgBox("Number Format Error")
    End Try

我想指定数字格式的例外。我怎么能这样做?

【问题讨论】:

  • 我不明白你所说的“数字格式”是什么意思,你能举一个有效和无效值的例子吗?

标签: vb.net exception exception-handling error-handling number-formatting


【解决方案1】:

您可以检查它是否是有效数字,而不是捕获异常

If Int32.TryParse(me.txtInterest.text, interest) AndAlso Int32.TryParse(me.txtPrincipal.text, principal) Then
    totalPayment = interest + principal
Else
    MsgBox("Number Format Error")
End If

【讨论】:

    【解决方案2】:

    使用此示例代码

       Try
                Dim no1 As Integer = Int16.Parse(Me.TextBox1.Text)
                Dim no2 As Integer = Int16.Parse(Me.TextBox2.Text)
                Dim toatlPayment As Integer = no1 + no2
    
    
            Catch ex As FormatException
                MessageBox.Show(ex.Message)
    
            End Try
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多