Introduction
This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError.
Messages with a severity level of 10 or less are informational and indicate problems caused by mistakes in information that a user has entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. Severity levels from 17 through 25 indicate software or hardware errors. When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.
The SqlConnection remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server usually closes the SqlConnection. However, the user can reopen the connection and continue. In both cases, a SqlException is generated by the method executing the command.
For information on the warning and informational messages sent by SQL Server, see the Troubleshooting section of SQL Server Books Online. The SqlException class maps to SQL Server severity.
Source Code
Below is the example for how to handle an SqlException in C#
public void ShowSqlException()
{
string mySelectQuery = "SELECT column1 FROM table1";
SqlConnection myConnection =
new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Sample;");
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
try
{
myCommand.Connection.Open();
}
catch (SqlException e)
{
string errorMessages = "";
for (int i=0; i < e.Errors.Count; i++)
{
errorMessages += "Index #" + i + "\n" +
"Message: " + e.Errors[i].Message + "\n" +
"LineNumber: " + e.Errors[i].LineNumber + "\n" +
"Source: " + e.Errors[i].Source + "\n" +
"Procedure: " + e.Errors[i].Procedure + "\n";
}
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = "My Application";
log.WriteEntry(errorMessages);
Console.WriteLine("An exception occurred. Please contact your system administrator.");
}
}