How to catch a specific SqlException error?
问题 Q: Is there a better way to handle SqlExceptions? The below examples rely on interpreting the text in the message. Eg1: I have an existing try catch to handle if a table does not exist. Ignore the fact that I could check if the table exists in the first place. try { //code } catch(SqlException sqlEx) { if (sqlEx.Message.StartsWith(\"Invalid object name\")) { //code } else throw; } Eg2: without the try catch showing duplicate key exception if (sqlEx.Message.StartsWith(\"Cannot insert duplicate