Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trap error or 'Resume Next'

I realise this is an older programming environment, but I have to clean up some VB6 code and I am finding that most of it uses:

On Error Resume Next

What is the general consensus about the use of On Error Resume Next?

Surely, if there is an error, you would want the app to stop what it was doing, rollback any data changes, and inform the user of the error, rather than just resuming.

When is it a good idea to use On Error Resume Next?

like image 654
CJ7 Avatar asked May 03 '10 10:05

CJ7


1 Answers

It is perfectly reasonable to use On Error Resume Next to implement local structured error handling. This involves testing for an exception and acting on it of course, as well as disarming the mechanism afterward. Example:

On Error Resume Next
GetAttr strFilePath
If Err Then
    On Error GoTo 0
    'Deal with "no file" scenario.
Else
    On Error GoTo 0
    'Open and process the file.
End If

That's just a simple example where only one sort of exception is expected. In some cases it is necessary to test Err.Number for specific values and take different actions based on them.

The unstructured approach based on GoTo label can often work as well, but it is hardly superior in most instances. In VBScript the pattern shown above is the only form of exception handling you even have since there are no GoTos or labels.

What's objectionable is arming explicit exception testing at the head of every procedure and ignoring it... a sort of Trust the Force, Luke approach to trying to mask coding errors.

like image 102
Bob77 Avatar answered Oct 04 '22 01:10

Bob77