2011-06-22 33 views
7

我想從文件中讀取,如果失敗,請讓用戶重試或以其他方式放棄。到目前爲止,代碼如下所示:如何使用Try和Catch重試VB.Net中的操作?

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 

我不喜歡Goto,它很醜。但我不知道如何製作一個跨越嘗試和捕捉的循環。

有沒有更好的方法來寫這個?

+0

+1主要是爲了擺脫goto的野心。 :) – Guffa

回答

8
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 
+1

但是,如果讀取成功,這將永遠持續下去!這是不同於代碼與goto – Eyal

+0

@Eyal良好的捕獲。固定! –

+1

或者您也可以初始化重試爲false並將循環更改爲重試時執行 – Eyal

2

我會將邏輯分成一個讀取函數,根據讀取結果返回true或false,然後處理該方法之外的重試邏輯。

例如

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 
3

我想到另一個答案:

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 

退出基本上轉到了僞裝,但是。這樣我也不需要另一個大範圍的變量。

+0

所有這些操作都會將消息框帶上「ok」按鈕。這不應該是一個是或否? –