我需要让这个try-catch方程运行多次,如果它检测到错误(输入字母或符号)我该怎么做?我尝试使用相同的代码进行第二次尝试捕获,但它不起作用。
Try
a = (Console.ReadLine())
Catch ex As Exception
Console.WriteLine("Type Integer only. Try again.")
End Try
我正在使用VB.Net '08版
答案 0 :(得分:3)
像JDB指出的那样,你不应该在正常流程中使用异常。 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
答案 1 :(得分:1)
您可以尝试将其置于具有以下条件的循环中:
bool tryAgain = true;
while(tryAgain){
try{
//your code here
}catch(Exception e){
//your exception here
}
}
另外,请确保您不会遇到无限循环,因此请检查您的while或循环条件是否正确。
答案 2 :(得分:0)
correct = false;
while(!correct){
Try
a = (Console.ReadLine())
correct = true;
Catch(Exception e){
Console.WriteLine("Type Integer only. Try again.")
continue;
}