6.5. Retrying Code

Sometimes it is necessary to rerun code that has triggered an error. Unfortunately, there is no good way to rerun code by using structured exception handling. Example 6-9 shows one method that uses nested Try blocks, which is ideal if you need to retry code only a few times.

Example 6-9. Retrying a method
Public Shared Sub Main( )
   
  Try
    RetryMethod( )
  Catch e As Exception
   
    Try
      RetryMethod( )
    Catch e As Exception
      'Fail
    End Try
   
  End Try
   
End Sub

Nested Try blocks are great unless you want to retry your code more than a few times. Beyond that, reading the code becomes more difficult. If someone has to scroll the code window out to column 420 to see what you have done—well, they will laugh at you and tell people about it on the elevator.

Try blocks are re-entrant, so you can use a Goto to jump back into a Try block that already executed. Example 6-10 demonstrates this technique.

Example 6-10. Retrying code after a failure
Imports System
   
Public Class App
   
  Public Shared Sub Main( )
   
    Dim attempts As Integer = 0
    Dim maxRetries As Integer = 5
   
    Try
      'Code to be retried n times
retry:
      attempts += 1
      Console.WriteLine("Attempt {0}", attempts.ToString( ))
   
      'Simulate error - jumps to Catch block
      Throw New Exception( )
   
    Catch e As Exception
   
      If attempts = maxRetries Then
        GoTo done
      End If
   
      GoTo retry
done:
    End Try
   
  End Sub
   
End Class

This code does not flow well, and it is difficult to read. It exists just in case someone out there decides to be clever. Stop trying to be clever when ...

Get Object-Oriented Programming with Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.