waqasahmed
waqasahmed

Reputation: 3835

A loop in a try..catch

Okay, I have a try..catch such that :

Try   
  Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
Catch ex As Exception
  sheet = InputBox("Re-enter table:")
  Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
End Try

The above will only work for the first instance. What I want to do is keep displaying the Input box until the dr is a success (i.e. values have been retrieved from the database.

I know I need some sort of while in the catch, but I am unsure how to proceed

Upvotes: 0

Views: 7440

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Have a look here why this is not a good idea.

If you are still interested, you can try this:

   Dim retries As Integer = 3
   While True
       Try
           Dim sheet as String = InputBox("Enter table:")
           Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & sheet, myConn)
           Exit While
       Catch
           retries -= 1
           If retries = 0 Then
               Throw
           Else
               System.Threading.Thread.Sleep(1000)
           End If
       End Try
   End While

Change the retries if you want more(infinite-> <=0), change or remove the thread.sleep if you want to retry immediately.

Upvotes: 2

Sebastien
Sebastien

Reputation: 100

Catch block has been designed to handle exceptions, not to execute database queries... You should use Jeff's way. The same I was writing, but he's quicker than I

Upvotes: 0

Jeff
Jeff

Reputation: 1955

This might work:

    Dim inputOk As Boolean = False

    Do Until inputOk = True
        Try
            Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
            inputOk = True
        Catch ex As Exception
            sheet = InputBox("Re-enter table:")

        End Try
        End
    Loop

Upvotes: 1

JediPotPie
JediPotPie

Reputation: 1068

Remove the performSelect from inside the catch block, otherwise you could throw an exception there too and it would need to be caught, etc. Put the entire try catch block inside the while loop and exit when you have a value for sheet.

Upvotes: 2

Related Questions