I got the following question via e-mail:
I want to catch timeout errors when I execute a script. Catching the error is easy, but I then want to retry 3 times. In VB6 I could just resume a command when I caught the error. How can I do this with vb 2008 using try..catch?
This is a case where two different techniques come into play. The first is using a number of Catch statements to allow you to catch specific types of exceptions. The second is to make essentially a recursive call to the function, with a counter to ensure that you don't end up in an infinite loop.
1: Module Module1
2: Sub Main()
7: End Sub
9: Private tryCounter As Integer = 0
10: Private maxAttempts As Integer = 3
11: Private Sub Foo()
13: If tryCounter = maxAttempts Then tryCounter = 0
14: tryCounter += 1
16: Catch toex As TimeoutException
17: If tryCounter = maxAttempts Then
18: Console.WriteLine("Too many failures.")
21: End If
22: Catch ex As Exception
24: End Try
25: End Sub
27: Private Sub FooWithTimeout()
28: Console.WriteLine("Attempt " & tryCounter)
29: Throw New TimeoutException
30: End Sub
31: End Module
I've called Foo() twice from Main() simply to show that the function resets the attempt counter properly.