Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 15,315 times

Related Categories

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

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments