Catch SQL Server Error Number

  • Thread starter Thread starter Roger Twomey
  • Start date Start date
R

Roger Twomey

I am familiar with the try catch block.

I am trying to use it more explicitly depending on the SQL Server error
raised. Is there a way to get the actual SQL server error message that was
raised when this occurs?

We can add our own custom errors but I need to be able to catch the number.
 
If you have something like the this, you can check the Number on the
SQLException sqlEX object. The plain ol' System.Exception doesn't have
the Number property. I *think* I have the catches in the right order.
I'm terrible at misplacing them in my own code so you may want to
experiment with that.

Try
' Do something
Catch sqlEx As SqlException
If sqlEx.Number = 8675309 Then
' Create custom Exception and throw
End If
Catch ex As Exception
' Some other error you weren't expecting
Finally
' do your finally stuff
End Try

There are actually more properties for the SQLException object like
Message, Procedure, Server, Source, State if any of those are of
interest to you.
 
Back
Top