Try Catch question

danyeungw

Well-known member
Joined
Aug 30, 2005
Messages
73
Programming Experience
10+
I ran into a problem. Please see code sample below:

Sub a()
try
For i = 0 to 10
Sub b
Next
catch ex as Exception
ErrorTrap
end try
end sub

Sub b()
try
......
catch
......
end try
end sub

if there an error occured in Sub b, Sub a would go to catch also and the For loop stopped. What can I do to let the For loop continue until i = 10?

Thanks.
Dan-Yeung
 
I think it may work if I move the Try Catch inside the For loop in Sub a. What do you think?

Sub a()
For i = 0 to 10
try
Sub b
catch ex as Exception
ErrorTrap
end try
Next
end sub

Thanks.
Dan-Yeung
 
Hi Dan-Yeung,
Can you be more specific please?
please explain what are you trying to accomplish there ... step by step as it is very confusing if i may :(

Usually try catch statement is used as it follows

VB.NET:
[color=blue]try[/color] 
[color=blue]for[/color] i = 0 [color=blue]to[/color] 10
[color=darkgreen]'do something ... [/color]
[color=darkgreen]'if exception occurs it will throw the same directly even if the rest of the code is not executed[/color]
[color=blue]Next[/color]
[color=blue]catch[/color] ex [color=blue]as[/color] exception 'note that it may be any other kind of exception
messageBox.Show(ex.Message)
[color=blue]Finally[/color]
[color=green]'code here will be always executed[/color]
[color=green]'usually programmers use finally to destroy objects, close connection/s etc. as it is always executed[/color]
[color=blue]End try[/color]


Regards ;)
 
kulrom - except if there is an error in the "do something" section, it won't continue on with the next loop iteration.... which I think is what he wants. Loop through 10 times, no matter what, even if there are errors, keep looping.

-tg
 
I see ... weird isn't ... why would someone likes to perform the code that has bug within?
Hmm ... then simply remove try catch statement if you don't want to find the exception anyway ... btw, TG thanks for the explanation. sometimes i'm really struggling with English ... but not all the time :D

Regards ;)
 
couldnt something like this be done?

VB.NET:
Sub A
  For i = 0 to 10
	Try
	   'Do the possibly error-ful code
	Catch
	   'If error do nothing and continue
	End Try
  Next i
End Sub
 
But if an error is thrown, you may want it to be handled.... but still continue....

As for why, we can only guess in this case, but I can see possibilities.... connecting to a remote server. If it times out and throws an error, handle it by logging it, but then continuing on with the next one in the list.... ?shrug?

-tg
 
Back
Top