如何为生成异常处理代码以确保数字输入?我正在为我的visual basic课程做期末考试,有一些错误我想让我的程序变得完美:)。很抱歉他们的标题真的很难制作。我想要它,这样当有人键入字符串而不是整数时,程序就不会关闭。
模块1
Sub Main()
Dim year, age, again As Integer
retry:
Console.WriteLine("Enter The year you were born in!")
Console.WriteLine("")
year = Console.ReadLine()
Console.WriteLine("")
If year < 1894 Or year > 2014 Then GoTo Toyoung
age = 2014 - year
Console.WriteLine("You are " & age & " years old")
Console.WriteLine("")
VB.NET中的异常处理通常是这样工作的。
随着每个过程的开始,你做这个
TRY
''Put some code here
CATCH
''Put code on what to do if it throws an error
FINALLY
''Optional: Any thing that has to be done regardless of wether it throws
''an exception or not. Usually here is where you would close the connection
END TRY
在您的情况下,您只需要Validate
用户输入即可。您需要做的是检查isnumber(nameoftextbox) = False
是否给用户一条消息并退出子程序。
一种方法是输入一个字符串,并用isnumeric
检查以确保它是数字的,如下所示:
Sub Main()
Dim year, age, again As Integer
Dim s as string
retry:
Console.WriteLine("Enter The year you were born in!")
Console.WriteLine("")
s = Console.ReadLine()
Console.WriteLine("")
if not isnumeric(s) then goto retry
year = s
If year < 1894 Or year > 2014 Then GoTo Toyoung
age = 2014 - year
Console.WriteLine("You are " & age & " years old")
Console.WriteLine("")
另一种方法是使用Try, Catch
块。有些人更喜欢它。