Library code snippets

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

Comments

  1. 07 Jan 2009 at 23:14
    For Error Handling in Asp.net you can read following article http://dotnetguts.blogspot.com/2007/10/error-handling-in-net-with-example.html
  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Error Handling.

Leave a comment

Sign in or Join us (it's free).

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 ...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback