3

how to catch sql exception with its error code(error no) to identify which exception is exactly thrown in c# ? for example database is offline or there is reference row in other table so sql wont allow me to delete row but how exactly i could identify what is the problem in catch so that i can display message to the user in my application

1
  • What library are you using to interact with the db? Commented May 18, 2011 at 5:10

2 Answers 2

8

You need to put your database code into a try ... catch block, and (assuming you're using ADO.NET against SQL Server) then catch the SqlException.

try
{
   // your database code here
}
catch(SqlException sqlEx)
{ 
   foreach(SqlError error in sqlEx.Errors)
   {
       // you can inspect the individual errors, their code etc. here
   }
}

The SqlException object will contain a collection of SqlError objects that describe the error that happened in great detail - with line number, error code and everything.

Other databases will have similar constructs - check your docs!

Sign up to request clarification or add additional context in comments.

Comments

1

There are specific numbers assigned to each type of exception in .net Exception class hierarchy you will find some useful material over here

1 Comment

Link returns "this page does not exist".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.