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
2 Answers
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!