Visual Basic中的输入不匹配异常 [英] Input Mismatch Exception in Visual Basic

查看:80
本文介绍了Visual Basic中的输入不匹配异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉Visual Basic中的异常处理。下面我有一个带有for-loop的代码片段。我的目标是在用户输入字符串而不是整数时抛出异常。如果有人能告诉我正确的try catch语句来实现这一目标,我将不胜感激。



I'm not familiar with exception handling in Visual Basic. Below I have a code snippet with my for-loop. My goal is to throw an exception if the user inputs a string instead of an integer. I would greatly appreciate if someone could show me the correct try catch statement to accomplish this.

For rowindex = 1 To myDataGridView.RowCount
            For columnindex = 1 To myDataGridView.ColumnCount
                    objWorkSheet.Cells(rowindex + 14, columnindex + 0) = myDataGridView(columnindex - 1, rowindex - 1).Value
            Next
        Next

推荐答案



你需要这样的东西,



例如:

Hi,
you need something like this,

For example:
Dim inputs As String() = {"1", "2", "3", "tr", "6", "tt", "500", "343", "AA"}
      Dim invalidinput As New List(Of String)
      Dim validinput As New List(Of String)
      For index = 0 To 10
          If (IsvalidNumber(inputs(index)) = True) Then
              invalidinput.Add(inputs(index))
          Else
              validinput.Add(inputs(index))
          End If
      Next

      If (invalidinput.Count > 0) Then
          ' do your stuff
      End If
      If (validinput.Count > 0) Then
          ' do your stuff
      End If





用户定义的功能:





User defined function:

    Public Function IsvalidNumber(ByVal value As Integer) As Boolean
    Dim flag As Boolean = False
    Dim number As Integer
    Try
        number = Convert.ToInt32(value)
        flag = True
    Catch ex As Exception
        ' Do nothing
    End Try
    Return flag
End Function





问候和感谢

Sarva



Regards and thanks
Sarva


请不要请不要抛出异常的用户输入错误。除非您正在编写DLL或其他无法与用户交互的其他内容,否则抛出异常是不对的。您应验证用户输入,如果错误,请告诉用户并要求他们更正。



错误处理异常导致应用程序崩溃,异常并不意味着用这种方式。只需使用消息框并停止处理,直到错误得到修复。
Please, please please do not throw exceptions for incorrect user input. Unless you are writing a DLL or something else that does not have any way of interacting with the user, throwing an exception is the wrong thing to do. You should validate the user input and if its wrong, tell the user and ask them to correct it.

Incorrectly handled exceptions cause application crashes, and exceptions are not meant to be used this way. Just use a message box and stop processing until the error is fixed.


这篇关于Visual Basic中的输入不匹配异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆