Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Try and Catch to retry an operation in VB.Net?

I'd like to read from a file and if I fail, let the user retry or otherwise give up. So far the code looks like this:

Read_Again:
    Try
        my_stream.Read(buffer, 0, read_len)
    Catch ex As System.IO.IOException
        If MessageBox.Show("try again?") = DialogResult.Retry Then
            GoTo Read_Again
        Else
            Application.Exit() 'just abort, doesn't matter
        End If
    End Try

I don't like the Goto, it's ugly. But I don't see how to make a loop that spans the try and catch.

Is there a better way to write this?

like image 825
Eyal Avatar asked Jun 22 '11 20:06

Eyal


1 Answers

Dim retry as Boolean = True
While retry
   Try
      my_stream.Read(buffer, 0, read_len)
      retry = False
   Catch ex As System.IO.IOException
       If MessageBox.Show("try again?") = DialogResult.Retry Then
           retry = True
       Else
           retry = False
           Application.Exit() 'just abort, doesn't matter
       End If
   End Try
End While
like image 175
Bala R Avatar answered Nov 14 '22 23:11

Bala R