Tuesday, August 24, 2004

On Error Resume Next considered dangerous

I was debugging some of the problems we came up with in VB Lite Unit, and I tracked one down to a wierd interaction between the test runner and the AssertKeyInCollection procedure I recently copied into VB Lite Unit from our project.

It seems that AssertKeyInCollection was passing, but not clearing the error number generated in the On Error Resume Next block. Also, the On Error Resume next block encompassed most of the procedure, when it only really needed to encompass one line to try to get the item from the collection, and another line to copy the error number to a variable, though that was not part of the problem.

Anyway, the test runner itself (until now anyway) used On Error Resume Next around the call to each test procedure, and examined the Err object afterward for exceptions. This turns out to be a bad idea since we now see that code in the tests can ignore a VB Error on purpose, but still leave the extraneous info in the Err object. In other words, after executing a procedure with On Error Resume Next in effect, it's entirely possible to have a value in Err.Number even though the procedure exited normally.

From now on, here's a couple of rules I'm going to follow...
1. If I ever use On Error Resume Next, I'll put Err.Clear at the end of the block.
2. I will not use On Error Resume Next to check error info raised from a procedure in the same project, since extraneous data can be in the Err object if the called code uses On Error Resume Next, and does not do Err.Clear. I'll always use an On Error Goto

1 Comments:

At 4:10 PM, Anonymous said...

I use this pattern:

On Error Resume Next
'Code where I don't care about failures...
On Error Goto 0

I like this better than Err.Clear because:
1. I was ignorant about Err.Clear
2. On Error Goto 0 looks better in this context.
3. Any unintended failures after On Error Goto 0 will not be supressed.

Thomas Eyde teyde@online.no

 

Post a Comment

<< Home