Reputation: 25
How can I make a Exception handling piece of code for to ensure numeric entry? I am doing my final for my visual basic class and there are some errors I would like to make my program perfect :). Sorry for the title they are really hard to make. I want it so the program doesnt close when someone types a string instead of a integer.
Module Module1
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("")
Upvotes: 1
Views: 300
Reputation: 15813
One way is to input a string, and check to make sure it's numeric with isnumeric
, like this:
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("")
An alternative method is to use a Try, Catch
block. It is preferred by some people.
Upvotes: 1
Reputation: 3834
Normally exception handling in VB.NET works this way.
With the start of each process you do this
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
In your case you just need to Validate
the user input. What you will need to do is to check to see if isnumber(nameoftextbox) = False
then give the user a message and exit the subroutine.
Upvotes: 3