Kym NT
Kym NT

Reputation: 790

Exception handling, Is this example good practice?

I mainly use the Try Catch in exception handling.. and use Exit Sub to terminate the method

In this code example:

What should be done to prevent Redundant code (i.e. commit and close connection)

'connect to DB

  Try

    'insert / update statement

  Catch ex as Exception

   'rollback
   'commit
   'closeDBConnection
      Exit Sub

  End Try

'commit
'close DBconnection

Is using Exit Sub a good practice ?

Upvotes: 2

Views: 59

Answers (2)

T.S.
T.S.

Reputation: 19350

Exit sub/return, or exception that occur within try - don't bypass finally block. Finally will complete still.

See this for full explanation https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

Upvotes: 1

Han
Han

Reputation: 3072

Put the commit statement at the end of Try block. Also use Finally block to do some cleanup.

Try
    ' insert / update statement
    ' commit
Catch ex As Exception
    ' rollback
Finally
    ' close DB connection
End Try

Upvotes: 1

Related Questions