Error Handling

This example illustrates the basics of error handling. Add the code below, with two command buttons cmdCreate and cmdDelete. First, try clicking cmdCreate. This will generate a message box saying that the path could not be found (unless you have a dir called C:fred), instead of VB generating and error... If your program was compiled to an EXE without error handling, your program would have closed... instead your user gets an error message, and your program continues to work! Likewise, if you click the Delete button, an error message is displayed, because the file does not exist...

The On Error Goto FileErr statement tells VB that if an error occurs, it should skip to the FileErr: statement, allowing you to 'trap' the error and deal with it accordingly.

Private Sub cmdCreate_Click()
    On Error GoTo FileErr
    Dim filenum As Integer
   
    filenum = FreeFile
   
    Open "C:fred ext.txt" For Output As filenum
    Close filenum
    Exit Sub
FileErr:
    Select Case Err
    Case 76
        MsgBox "Path not found", , "Error"
    Case Else
        MsgBox "Unexpected error. Err " & Err & " : " & Error, vbOKOnly, "Error"
    End Select
End Sub

Private Sub cmdDelete_Click()
    On Error GoTo FileErr
    Kill "C:fred ext.txt"
    Exit Sub
FileErr:
    Select Case Err
    Case 53
        MsgBox "File not found", , "Error"
    Case Else
        MsgBox "Unexpected error. Err " & Err & " : " & Error, , , "Error"
    End Select
End Sub

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra