Using Exception Handling to Retry an Operation

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()
  3:         Foo()
  4:         Console.ReadLine()
  5:         Foo()
  6:         Console.ReadLine()
  7:     End Sub
  8: 
  9:     Private tryCounter As Integer = 0
 10:     Private maxAttempts As Integer = 3
 11:     Private Sub Foo()
 12:         Try
 13:             If tryCounter = maxAttempts Then tryCounter = 0
 14:             tryCounter += 1
 15:             FooWithTimeout()
 16:         Catch toex As TimeoutException
 17:             If tryCounter = maxAttempts Then
 18:                 Console.WriteLine("Too many failures.")
 19:             Else
 20:                 Foo()
 21:             End If
 22:         Catch ex As Exception
 23:             Throw
 24:         End Try
 25:     End Sub
 26: 
 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.

Print | posted @ Thursday, December 18, 2008 9:37 AM

Comments on this entry:

Gravatar # re: Using Exception Handling to Retry an Operation
by Jason Bock at 12/18/2008 11:44 AM

Why are you catching the general exception type? And why are you just throwing it after you catch it?
Gravatar # re: Using Exception Handling to Retry an Operation
by Jeff Certain at 12/18/2008 11:52 AM

Part of my rationale for leaving it there is that the asker sounds like they're already catching exceptions in their current code, and I wanted to emphasize that different exception types could be caught separately, rather than the VB6 technique of putting a Select...Case or If...Then statement in OnError. It also leaves a spot for them to hang their existing exception handling.

Other than that, there's really no compelling reason to leave it there.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: