Error Handling

Trapping errors on the next line

All errors can be identified by a unique error id. You can use this id to tell which error occurred, and to give a suitable error message. The simplest way to catch and error is the On Error Resume Next statement. When an error occurs, the error number is stored in the Variable Err, and code execution continues as if nothing has happened. If you know an error is likely to occur on a certain line, you can write some code which can catch this error.

The following code attempts to delete the file C:\test.txt. If it does not exist it displays a message saying so.

Sub Command1_Click
   On Error Resume Next ' Enable error trapping
  
   Kill "C:\test.txt"
   If Err = 53 Then ' The File Not Found error occurred
      Msgbox "C:\test.txt was not found"
   End If
End Sub

The error code for File Not Found is 53, and as that was the last error to occur, it was stored in the variable Err.

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.

“Engineers are all basically high-functioning autistics who have no idea how normal people do stuff.” - Cory Doctorow