een voorbeeld met try catch
Visual Basic Code:
Private Function IsValidInteger(ByRef result As Integer, ByVal txt As TextBox, ByVal fieldname As String, Optional ByVal minvalue As Integer = Integer.MinValue, Optional ByVal maxvalue As Integer = Integer.MaxValue) As Boolean
' Check for blank entry.
Dim numitemstxt As String = txt.Text
If numitemstxt.Length < 1 Then
MessageBox.Show("Please enter " & fieldname & ".")
txt.Focus()
Return False
End If
' See if it's numeric.
If Not IsNumeric(numitemstxt) Then
MessageBox.Show(fieldname & " must be a number.")
txt.Select(0, numitemstxt.Length)
txt.Focus()
Return False
End If
' Assign the value.
Try
result = Integer.Parse(txt.Text)
Catch ex As Exception
MessageBox.Show("Error in " & fieldname & "." &
vbCrLf & ex.Message)
txt.Select(0, numitemstxt.Length)
txt.Focus()
Return False
End Try
' Check that the value is between minvalue and maxvalue.
If result < minvalue Or result > maxvalue Then
MessageBox.Show(fieldname & " must be between " &
minvalue.ToString & " and " & maxvalue.ToString & ".")
txt.Select(0, numitemstxt.Length)
txt.Focus()
Return False
End If
' The value is okay.
Return True
End Function
' Validate the value.
Private Sub btnValidateClick() Handles btnValidate.Click
Dim thevalue As Integer
' See if the value is valid.
If Not IsValidInteger(thevalue, txtValue, "Value", 1, 10) Then Exit Sub
' In a "real" application, you would perform other processing here.
' ...
MessageBox.Show("OK")
End Sub