开发者

Identify sql exception in c#?

how to catch sql exception with its error code(error no) to identify which exception开发者_Go百科 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


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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜