「期望的結束語」意味着您給出的代碼行比期望的更多。在這種情況下,這是因爲Try
必須在自己的路線上。
對於確定用戶是否輸入整數的問題,將文本轉換爲整數的有用方法是Int32.Parse和Int32.TryParse方法。如果出現錯誤,前者會拋出異常,而後者將返回布爾值,指示解析是否成功。
「NullReferenceException」不是您想要捕捉的內容:您應該查閱可能拋出異常的方法的文檔,以查看它可以拋出哪些異常。有時,它足以趕上任何例外:
Module Module1
Sub Main()
Dim b As String
Dim isGoodNumber As Boolean = True
Dim radius As Integer
' OPTION ONE: Decline any bad input with a generic error message.
Do
b = InputBox("Please enter the radius as a whole number:")
Console.WriteLine("You entered {0}", b)
Try
radius = Integer.Parse(b)
isGoodNumber = True
Catch ex As Exception
isGoodNumber = False
End Try
If Not isGoodNumber Then
Console.WriteLine("Please enter a whole number.")
End If
Loop Until isGoodNumber
Console.ReadLine()
End Sub
End Module
如果要執行取決於被拋出什麼樣的錯誤不同的操作,您可以使用多種Catch
條款:
Module Module1
Sub Main()
Dim b As String
Dim isGoodNumber As Boolean = True
Dim radius As Integer
' OPTION TWO: Decline any bad input with a more specific error message.
Do
b = InputBox("Please enter the radius as a whole number:")
Console.WriteLine("You entered {0}", b)
Try
radius = Integer.Parse(b)
isGoodNumber = True
Catch ex As ArgumentNullException
isGoodNumber = False
Console.WriteLine("Please enter a whole number.")
Catch ex As FormatException
isGoodNumber = False
Console.WriteLine("Please enter a whole number.")
Catch ex As OverflowException
isGoodNumber = False
Console.WriteLine("Please enter a whole number between {0} and {1}", Integer.MinValue, Integer.MaxValue)
End Try
Loop Until isGoodNumber
Console.ReadLine()
End Sub
End Module
在這種情況下,如果您不需要提供錯誤的輸入相關錯誤消息,則甚至不需要拋出異常的可能性:
Module Module1
Sub Main()
Dim b As String
Dim isGoodNumber As Boolean = True
Dim radius As Integer
' OPTION THREE: A shorter way of option one.
Do
b = InputBox("Please enter the radius as a whole number:")
Console.WriteLine("You entered {0}", b)
isGoodNumber = Integer.TryParse(b, radius)
If Not isGoodNumber Then
Console.WriteLine("Please enter a whole number.")
End If
Loop Until isGoodNumber
Console.ReadLine()
End Sub
End Module
Try/Catch定義了一個塊 - 所有的代碼都應該放在裏面。你不能指定一個聲明來嘗試這種方式,如果這就是你正在嘗試做的事 – Plutonix
你將b除以零,你不能這樣做。你究竟想要做什麼? –
您還需要啓用Option Strict。 InputBox返回一個字符串,你(顯然)試圖對它進行數學運算。我不知道你想用'(b \ 0 + 1 = 1)'來做什麼,但它錯了。你需要分配結果,但是你應用的任何測試都是錯誤的。你真的不需要嘗試/趕上 – Plutonix