On error resume next bug

N

Neo

I found on error resume next doesn't work in for each... e.g.

on error resume next
for each x in y
'do stuff
next

if you have an error in for each loop, it falls in infinite loop... it
doesn't move to next element... this sad thing but, it's indication
that we must move to try catch instead of on error.
-Neo
 
M

Michael D. Ober

It works for me.

'VB 2005
Sub Main()
On Error Resume Next
Dim c As New Collection
c.Add(1)
c.Add(2)
c.Add("A")
c.Add(3)
c.Add("B")
Dim i As Integer
Dim v As Object
i = 0
For Each v In c
i = i + v
Debug.Print(i)
Next
Debug.Print(i)
End Sub

I wrote and tested this code in both VB 6 and 2005. The real issue here is
the use of the On Error Resume Next statement. It should be replaced
whereever feasible with try catch statements.

Mike.
 
N

Neo

But does it really raise error? If yes, after error does it move to
next element?

My error was during traversing graphs collection in excel worksheet.The
problem I had when there was an error which made the infinte loop. I am
not sure if that was only to do with that particualar access, bottom
line is say bye, bye to "on error resume next"
 
M

Michael D. Ober

Yes, it raises a "First Chance Exception" and then loops to the next item.
I don't know if the Excel Graphs collection is a true COM collection. You
may be better off using

For i as Integer = 0 to Graphs.Count -1
dim gr as Excel.Graph = Graphs(i)
' Do something with gr
next i

Having worked with Excel, I have discovered that some of Excel's collections
are true COM collections and others require using the count method above.

You are correct in that you really need to dump On Error Resume Next. You
should also add "Option Explicit On" and "Option Strict On" at the top of
all your code modules. This will allow the VB compiler to find and flag all
sorts of variable typing errors. You'll be surprised at how many common VB
6 constructs are simply dangerous - Option Strict On will catch 99+% of
them.

Mike.
 
N

Neo

Yes, I fully agree with you. I was still usin "on error resume next"
since it was easier. but if it doesnt' work even in one case, shouldn't
be used. Also, once you "on error" you can't use try catch.. that sux.
better not to use "on error".

about option strict and option explicit. I have been always using them.
Thanks for suggesting that, it might be useful to other VB 6 developer
who don't use it.
-Neo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top