开发者

How do I handle errors caused by invalid user input in a VB.NET program?

I am a beginner in VB.NET and I would like to know how do I handle the errors that may appear from the user of my program. For example, I 开发者_C百科have an triangle area program in wich I ask the user of the program to insert the length of the base and height of the triangle in a textbox. But what if he inserts a letter or something else, like a sign....my program will crash...

I know that one method would be to use On Error GoTo but I don't know how. If maybe you can direct me to some link or you could explain how do I handle errors, I would be grateful. Maybe you can even show me other ways to avoid errors from the user input.

This is my small program so far:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
                Handles Button1.Click

    Dim , Height, ARIA As Integer

    Base = TextBox1.Text
    Height = TextBox2.Text
    ARIA =  Base * Height / 2
    TextBox3.Text = ARIA

End Sub


What you need to do is:

Try
    'Do something dangerous
Catch ex As System.Exception 'catch any error
    'Handle the error here
End Try

If you have any "clean-up" tasks that need to be performed regardless of if any errors occurred (like closing a file, for instance), do:

Try
    'The dangerous code here will get executed
Finally
    'Whether the code throws any exception or not, this part will ALWAYS run
End Try
'If there was any error, then it would be thrown AFTER the end of the 'finally'

You can also have more complex exception handlers, like:

Try
    'Dangerous code
Catch ex As FormatException
    'This code catches only a FormatException
Catch ex As ArithmeticException
    'This code catches only ArithmeticException
'Any other kind of error is NOT caught
Finally
    'Regardless of whether the error was handled, this part will execute
End Try
'Unhandled exceptions will be thrown before the block continues


In addition to what the others already wrote, I figured it might be instructive for you to see what your code would look like using "Visual Basic best practices". You might not be ready for all of this yet, but maybe you find some of the concepts useful:

' This is at the top of the file and forces us to do explicit instead
' of implicit conversions. You can also set this in the project settings
Option Strict On    

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Handles Button1.Click

    ' It's convention to have local variables start with a lower-case character
    Dim base, height, aria As Integer 

    Try
        ' Since Option Strict is on, we need to explicitly convert
        ' Strings to Integers.
        base = Integer.Parse(TextBox1.Text) 
        height = Integer.Parse(TextBox2.Text)

    ' The documentation of Int32.Parse (Integer is a Visual Basic alias for
    ' Int32) says that a FormatException and an OverflowException can occur,
    ' so we catch and handle them here.
    Catch ex As FormatException
        MsgBox("Base or Height is not a number")
        Return   ' Leave the sub '

    Catch ex As OverflowException
        MsgBox("Base or Height is too large")
        Return
    End Try

    aria = base * height / 2
    TextBox3.Text = aria.ToString()    ' Convert the Integer back into a String

End Sub

Alternatively, you can use TryParse to convert an Integer into a String. It will not throw an exception but rather return false if the conversion fails:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Handles Button1.Click

    Dim base, height, aria As Integer 

    If Integer.TryParse(TextBox1.Text, base) = False OrElse Integer.TryParse(TextBox2.Text, height) = False Then
        MsgBox("Base or Height is invalid")
        Return
    End If

    aria = base * height / 2
    TextBox3.Text = aria.ToString()
End Sub

That way, you avoid exception handling altogether (in this case).


Your homework should look like this...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim Base, Height, ARIA As Integer
    Try
        Base = TextBox1.Text
        Height = TextBox2.Text
        ARIA = Base * Height / 2
        TextBox3.Text = ARIA
    Catch ex As Exception
        MessageBox.Show("Please enter a number")
    End Try
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜