0

I have code that will be for example

Dim cmd As New SqlClient.SqlCommand(commandString, databaseString) 
Dim result As Integer

Try
    result = cmd.ExecuteScalar()
Catch e as Exception
    'catch exception code
End Try

Instead of doing that, can I override the ExecuteScalar function to do some kind of generic exception catching?

salfasano
  • 277
  • 2
  • 11

3 Answers3

1

No, but you can create a generic DoExecuteScalar helper function that takes a SQL string and connection string:

Public Function DoExecuteScalar(commandString as String, databaseString as String) as Object
    Dim cmd as New SqlClient.SqlCommand(commandString, databaseString)
    Dim result as Integer
    Try
        result = cmd.ExecuteScalar()
    Catch e As Exception
        Return 0
    End Try
    Return result
End Function
mellamokb
  • 56,094
  • 12
  • 110
  • 136
1

No you cannot override methods because you cannot inherit from it since SqlCommand is sealed.

What's wrong with catching (or throwing) exceptions where you're using the SqlCommand?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You could also use composition:

Public Class SqlCommandManager
Private _sqlCommand As System.Data.SqlClient.SqlCommand
Public Sub New(command As System.Data.SqlClient.SqlCommand)

    If command Is Nothing Then
        Throw New ArgumentNullException("command")
    End If

    _sqlCommand = command
End Sub
Private ReadOnly Property Command As System.Data.SqlClient.SqlCommand
    Get
        Return _sqlCommand
    End Get
End Property
Public Function ExecuteScalar() As Object
    Dim result As Object

    Try
        result = Command.ExecuteScalar()
    Catch e As Exception
        'catch exception code
    End Try

    Return result
End Function
End Class

Not saying this is the best alternative, just that it is one ....

ssis_ssiSucks
  • 1,476
  • 1
  • 12
  • 11