0

如果输入了字母,或者它作为数字超出范围,我有这行代码来捕获异常,但是我添加了 WHEN 以避免捕获数字数据。现在我如何在我的案例语句之前使用异常错误来使用它以避免运行代码两次,因为一旦案例代码通过它将运行一个清晰的 txtbox,它已经被 try catch 处理了,不要如果这对你来说很清楚,但我理解。这是部分代码...

    Try
        'Integer Levels: intLvls is egual to the assigned text box, the first one from
        'the top, this line of code allow the user input to be captured into a variable.
        intLvls = txtBoxLvl.Text
    Catch ex As Exception When IsNumeric(intLvls)
        ErrTypeLetterFeild1()
    Finally
        analysingvalues1()
    End Try

我想做的事情:使用循环直到引用异常错误以避免运行以下代码部分:

 Private Sub analysingvalues1()
    Do Until IsNumeric (ex As Exception)<------how do i do this???

    Loop

代码的案例部分:

Select Case intLvls
        'User is prompt with the following label: lblLvl "Level of salespersons 1 - 4"
        'to make a choice from 1 to 4 as available values.
        Case 1 To 4
            'This line regulates the range of acceptable values, first textbox: must be egual
            'or higher than 1 and lower or egual to 4. Upon such rules a validation becomes
            'correct and is directed to the isValidCalculation sub.
            isValidCalculation()
        Case Is < 1
            ErrType1NumberRangeFeild()
        Case Is > 4
            ErrType1NumberRangeFeild()
        Case Else
            If txtBoxLvl.Text = "" Then
                ErrTypeClear1()
            Else
                If Not IsNumeric(txtBoxLvl.Text) Then
                    ErrType1NumberRangeFeild()
                Else
                    ErrTypeLetterFeild1()
                    ErrTypeClear1()
                End If
            End If
    End Select 'Ending choices.
End Sub

谢谢你的帮助!

4

1 回答 1

3

如果你打开 Option Strict 这个:

intLvls = txtBoxLvl.Text

将不再编译。这应该告诉你,你做的事情很臭。

开启选项严格

正确的解决方案是不要盲目地让运行时为您将 string 转换为 int,并捕获异常。

当您将字符串用户输入转换为整数时,错误输入并不是一种例外情况,这是您应该期待和防御性编码的情况。

我会把它改写成这样的:

    'Integer Levels: intLvls is egual to the assigned text box, the first one from
    'the top, this line of code allow the user input to be captured into a variable.

    if integer.TryParse( txtBoxLvl.Text, intLvls )
        analysingvalues1()
    else
        ErrTypeLetterFeild1()

编辑 - 正如下面 Chris 所指出的,我的意思是 Option Strict。我建议使用但 Explicit 和 Strict,并在可用时进行 Infer。

于 2012-04-07T02:30:57.503 回答