The best way to repeat an expression in which there was an exception from vb.net

Usually I do something like this:

    Dim Attempts = 0
    Try
Retry:
        <Block>
    Catch
        If Attempts < 3 Then
            Attempts += 1
            Thread.Sleep(2000)
            GoTo Retry
        Else
            Throw
        End If
    End Try

It really looks bad for me, but I don’t know how best to do it.

+3
source share
5 answers

I think poor use, I use this one and it is much cleaner.

Dim maxAttempt As Integer = 2

For i As Integer = maxAttempt To 0 Step -1

 Try
    ...
    'Successful Quit
    Exit For

  Catch
     Thread.Sleep(2000)

  End Try
Next 
+2
source

You can also try the following:

Dim retryCount as Integer = 0
Dim wasSuccessful as Boolean = False

Do
    Try
        <statements>
        'set wasSuccessful if everything was okay.'
        wasSuccessful = True
    Catch
        retryCount +=1
    End Try
Loop Until wasSuccessful = True OrElse retryCount >=5

'check if the statements were unsuccessful'
If Not wasSuccessful Then
    <do something>
End If

It will retry up to five times if the statements were not successful, but will immediately exit the loop if the statements were successful.

+3
source

For While, GoTo, . , .

+2

, , . @0xA3.

"", , :

    Sub TryExecute(Of T As Exception)(ByVal nofTries As Integer, 
                                      ByVal anAction As Action)
        For i As Integer = 1 To nofTries - 1
            Try
                anAction()
                Return
            Catch ex As T
                Thread.Sleep(2000)
            End Try
        Next
        ' try one more time, throw if it fails
        anAction()
    End Sub

:

TryExecute(Of SomeExceptionType)(3, Sub()
                                      <Block>
                                    End Sub())

VB 10, .Net 3.5/VB 9,

+2

, -, , . .

, , :

+1

Source: https://habr.com/ru/post/1760486/


All Articles