Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

In visual basic, How to you return to the original while loop when I am using a Try Catch to error check?

I am reading a text file that has numbers. I am using a Try Catch to catch if one of the lines is not an Integer. I am not allowed to you an "Integer.TryParseInt". If it finds a non integer, it goes to an "InvalidCastException" and gives an message box stating the error. I need it to catch the error, give an error message,ignore the line, and return to the original while loop and finishes reading in the rest of the lines.

I am sure it is something simple that I am missing.

Thanks for any help.

Here is the code I have so far:

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

Dim MyReader As StreamReader

Dim Line As String

Dim sum As Integer

Try

MyReader = File.OpenText(TextBox3.Text)

Do Until MyReader.EndOfStream

Line = MyReader.ReadLine()

sum += CInt(Line)

Loop

Catch ex As FileNotFoundException

MessageBox.Show("You entered: " & (TextBox3.Text) & " Could not find file! Make sure you entered it correctly)

TextBox3.Clear()

TextBox3.Focus()

Catch ex2 As DirectoryNotFoundException

MessageBox.Show("Could not find directory! Make sure you entered it correctly.")

TextBox3.Clear()

TextBox3.Focus()

Catch ex3 As InvalidCastException

MessageBox.Show("This line =" & (Line) & " and is not a number")

Resume Next

End Try

Label6.Text = (sum)

End Sub

Update:

I must use a Try Catch for this exercise.

Update 2:

I must use a Try Catch for this exercise.

1 Answer

Relevance
  • 9 years ago
    Favorite Answer

    Why don't you put the 'TRY' block inside the WHILE loop?

    Source(s): Personal experience
Still have questions? Get your answers by asking now.