开发者

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

开发者 https://www.devze.com 2023-03-15 05:20 出处:网络
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:

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?


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


I thought of another answer:

Do
    Try
        my_stream.Read(buffer, 0, read_len)
        Exit Do
    Catch ex As System.IO.IOException
        If MessageBox.Show("try again?") <> DialogResult.Retry Then
            Application.Exit() 'just abort, doesn't matter
        End If
    End Try
Loop

Exit is basically Goto in disguise, however. This way I don't need another variable with a large scope, too.


I would separate the logics into one reading function which returns true or false depending on the outcome of the read and then handle the retry logics outside that method.

For example

Function performOneRead(buffer) as Bool
   Try      
     my_stream.Read(buffer, 0, read_len) 
     return true 
   Catch ex As System.IO.IOException    
     return false       
 End Try
End Function


Sub ReadLogics()
 Dim ok as Bool

 While Not Ok
   ok = performOneRead(buffer)
   if not ok AndAlso MessageBox.Show("try again?") <> DialogResult.Retry then Application.Exit(1)
 End While 
end sub
0

精彩评论

暂无评论...
验证码 换一张
取 消