How can I get an error message that happens when using ExecuteNonQuery()?

Haider Ali Wajihi picture Haider Ali Wajihi · Aug 11, 2011 · Viewed 40.5k times · Source

I am executing a command in this way :

var Command = new SqlCommand(cmdText, Connection, tr);

Command.ExecuteNonQuery();

In the command there is an error, however .NET does not throw any error message. How could I know that the command did not executed properly, and how to get the exception?

Answer

Marc Gravell picture Marc Gravell · Aug 11, 2011

.NET does indeed raise an error message... if the severity is 16 or above (since it throws an exception) - the message will be in the exception .Message. If you are using RAISERROR with a lower severity (or using PRINT) then you will have to subscribe to the InfoMessage event on the connection.