2013-12-18 71 views
2

如果檢測到錯誤(輸入字母或符號),我需要讓這個try-catch方程運行多次,如何獲得那?我試着用相同的代碼嘗試第二次嘗試,但它沒有奏效。如何讓try-catch方程運行多次#

Try 
     a = (Console.ReadLine()) 
    Catch ex As Exception 
     Console.WriteLine("Type Integer only. Try again.") 
    End Try 

我使用VB.Net '08版

+0

也許是一個For循環?或者你可以使用While循環。嘿...... [任何舊的循環應該做的](http://msdn.microsoft.com/en-us/library/ezk76t25.aspx)。 – JDB

+1

這裏有幾個問題。首先,你真的[不應該依賴於隱式轉換](http://www.owenpellegrin.com/articles/vb-net/converting-strings-to-numbers/)。其次,例外不應該是您正常工作流程的一部分。如果用戶可能鍵入非整數,則不要使用異常來捕獲非整數...使用正確的邏輯(如[If If Int32.TryParse()'](http://msdn.microsoft.com /en-us/library/f02979c7.aspx)) – JDB

回答

3

像加多寶指出,你不應該在正常流量使用異常。 ReadLine返回一個字符串,而不是一個整數。

Do 
     Dim input As String 

     input = Console.ReadLine() 

     If Int32.TryParse(input, a) Then 
      Exit Do 
     End If 

     Console.WriteLine("Type Integer only. Try again.") 
    Loop 
+0

謝謝。像魅力一樣工作! :d –

1

您可以嘗試把它在一個循環中包含一些條件:

bool tryAgain = true; 
while(tryAgain){ 
try{ 
    //your code here 
}catch(Exception e){ 
    //your exception here 
} 
} 

也不要請確保您不運行進入無限循環,所以請檢查你的while或循環條件是否正確。

+0

確保你記得在沒有錯誤發生時將tryagain變量設置爲false。 –

0

Java Solution

correct = false; 

while(!correct){ 
    Try 
    a = (Console.ReadLine()) 
    correct = true; 
    Catch(Exception e){ 
    Console.WriteLine("Type Integer only. Try again.") 
    continue; 
}