Error Handling

Error Handling for the whole procedure

In a complex procedure, you will find there are lots of places where errors can occur, and quite often are the same errors. If this is the case putting code after each line is a waste of space and time. A much more efficient way is to use the statement:

On Error GoTo LineLabel

This statements tell visual basic, that if an error occurs after this statement, to continue code execution at the LineLabel specified. The following code attempts to delete A: est.txt (this assumes A: is a disk drive). If an error occurs, it will give the appropriate error message. It will then attempt to get the size of C:fred.txt . Again, if an error occurs it will give the appropriate message. However it all uses the same code to detect the error.

Sub Command1_Click()
   ' If an error occurs GoTo FileError
   On Error GoTo FileError
  
   ' Attempt to delete A: est.txt
   Kill "A: est.txt"

   ' Attempt to get the size of C: est.txt
   gFileSize = FileLen("A: est.txt")

   Msgbox "File Size is: " & gFileSize

   ' Exit the procedure as no error has occurred
   Exit Sub

FileError:
   Select Case Err
   Case 53
       ' The file does not exist. Inform the user
      Msgbox "The file does not exist"
      gFileSize = "<Unknown>"
   Case 5
      ' The disk is not ready. Prompt user for action
      Ans = Msgbox ("Insert a disk into Drive A", vbAbortRetryIgnore)
      If Ans = vbRetry Then
         ' The user chose Retry. Resume code execution
         ' at where the error occurred
         Resume
     ElseIf Ans=vbIgnore Then
       ' The user chose to ignore. Resume code execution
         ' at the line after where the error occurred
         Resume Next
      Else
         ' The user chose abort. Exit this procedure
         Exit Sub
      End If
   Case Else
        ' unexpected error
      Msgbox "An error occurred. " & Err & " : " & Error
   End Select
End Sub

FileLen returns the size of the specified file in bytes. Normally Err 75 would occur if the drive was not ready, however when using FileLen Err 5 occurs

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

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

Interested in writing for us? Find out more.

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.

“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook