Trapping errors in Visual Basic

If you keep coming up with problems in your applications and you don’t want error messages to be popping up when the user causes an error then all you need to do is add an error handler. In fact, you should be doing this anyway, just in case errors come up.

On Error

There are two options from here. You can either get it to ignore the error or do something else that sorts the error out. If you just want the error to be ignored use this.

On Error Resume Next

This will simply execute the next line of code after one with the error on. This could stop your application doing something important but lets face it, however there are times when you legitimately want to stop an error and ignore it. Usually it is just used then there is a problem such as when you are using the web browser control and a user clicks back when there is no page to go back to. This would normally bring up an error box but by adding in the code it stops this from happening.

Your other alternative is to add in a GOTO command to send the code to do something else if it finds an error. Take a look at this example.

On Error Goto 10
WebBrowser1.GoBack
Exit Sub
10 ' error bit
MsgBox ("Error!")
' some code to sort it out
End Sub
Timeline

Newsletter

Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.

Metadata

Tags: , , ,

This entry was posted on Thursday, December 30th, 2004 at 4:07 pm and is filed under Programming, Tech. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.