Results 1 to 5 of 5

Thread: Need help with Try, Catch and Finally

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2003
    Posts
    47

    Need help with Try, Catch and Finally

    Hi all. I have a For loop that processes a list of tasks inside the Try and Catch scope. Whenever there's an error/exception occurs in the Try scope, the error can be traced in the Catch scope. However, I wanted to compile a list of errors to be shown to the user and continue performing the next tasks. How do i do so? For example if i wanted to delete a list of records in the database:

    Code:
    Dim cmDelete As New SqlCommand
    Dim i As Integer
    
    Try
        If cnDatabase.State = ConnectionState.Closed Then
             cnDatabase.Open()
        End If
    
        cmDelete.Connection = cnDatabase
        cmDelete.CommandText = "DELETE FROM Users WHERE ID=@ID"
        cmDelete.Parameters.Add("@ID", SqlDbType.Int)
    
        For i = 0 To 10
            cmDelete.Parameters("@ID").Value = i
            cmDelete.ExecuteNonQuery()
        Next
    
    Catch ex As Exception
        'Error goes here
    Finally
        cnDatabase.Close()
    End Try
    How do i return from the Catch scope to the For loop? As i know whenever an error occurs it will jump to the Catch scope and execute whatever statements there and proceeds to Finally. Thanks in advance.

  2. #2
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    See if 'GoTo' would help you , though I don't know why you're doing that . Even if it works , you can't say this is a fix for this problem .

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2003
    Posts
    47
    I have thought of using the 'Goto' but is there a better way for this? Why am i doing this? My objective is to proceed with the next task whenever an error occurs and compile a list of errors and display it to the user. (In this case show the user on which record has not been successfully deleted).

    Thanks. Any help would be great.

  4. #4
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985
    When an error is thrown in a try block, it goes to the catch block then resumes the code directly after the catch block.

    Just put a try and catch block in the for loop so each time the loop runs, if an error is thrown you can document it, if no error is thrown then it runs normally and in both cases, it will continue in the loop until the loop ends.

  5. #5
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    How about On Error Resume Next !! . I know these tips are bad programming but this is how you want it to be .

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width