我有这行代码来捕获异常,如果输入一个字母,或者它是一个数字,但我已经添加了WHEN以避免捕获数字数据。现在我如何使用异常错误在我的case语句之前使用它以避免运行代码两次,因为一旦案例代码通过它将运行一个已经由try catch处理的清除txtbox,don`如果这对你来说很清楚,但我明白了。这是部分代码......
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
请求帮助!
答案 0 :(得分:3)
如果启用Option Strict this:
intLvls = txtBoxLvl.Text
将不再编译。这应该告诉你,你做了一些臭的事。
启用Option Strict
正确的解决方案不是盲目地允许运行时为您将字符串转换为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。我建议使用但是显式和严格,如果可用则推断。