Export (0) Print
Expand All

SqlException Class

The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited.

For a list of all members of this type, see SqlException Members.

System.Object
   System.Exception
      System.SystemException
         System.Data.SqlClient.SqlException

[Visual Basic]
<Serializable>
NotInheritable Public Class SqlException
   Inherits SystemException
[C#]
[Serializable]
public sealed class SqlException : SystemException
[C++]
[Serializable]
public __gc __sealed class SqlException : public SystemException
[JScript]
public
   Serializable
class SqlException extends SystemException

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

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.

Example

[Visual Basic, C#, C++] The following example generates a SqlException due to a missing server, and then displays the exception.

[Visual Basic] 
Public Sub ShowSqlException()
     Dim mySelectQuery As String = "SELECT column1 FROM table1"
     Dim myConnection As New SqlConnection ("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Sample;")
     Dim myCommand As New SqlCommand(mySelectQuery, myConnection)

     Try
         myCommand.Connection.Open()
     Catch e As SqlException
         Dim errorMessages As String
         Dim i As Integer

         For i = 0 To e.Errors.Count - 1
             errorMessages += "Index #" & i.ToString() & ControlChars.NewLine _
                            & "Message: " & e.Errors(i).Message & ControlChars.NewLine _
                            & "LineNumber: " & e.Errors(i).LineNumber & ControlChars.NewLine _
                            & "Source: " & e.Errors(i).Source & ControlChars.NewLine _
                            & "Procedure: " & e.Errors(i).Procedure & ControlChars.NewLine
         Next i

        Dim log As System.Diagnostics.EventLog = New System.Diagnostics.EventLog()
        log.Source = "My Application"
        log.WriteEntry(errorMessages)
        Console.WriteLine("An exception occurred. Please contact your system administrator.")
     End Try
 End Sub

[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.");
   }
}

[C++] 
public:
 void ShowSqlException() 
 {
    String* mySelectQuery = S"SELECT column1 FROM table1";
    SqlConnection* myConnection =
       new SqlConnection(S"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Sample;");
    SqlCommand* myCommand = new SqlCommand(mySelectQuery,myConnection);

    try 
    {
       myCommand->Connection->Open();
    }
    catch (SqlException* e) 
    {
      String* errorMessages = S"";

      for (int i=0; i < e->Errors->Count; i++)
      {
          errorMessages = String::Concat(
             errorMessages,
             String::Format( S"Index #{0}\nMessage: {1}\nLineNumber: {2}\n",
                __box(i), e->Errors->Item[i]->Message, __box(e->Errors->Item[i]->LineNumber)),
             String::Format( S"Source: {0}\nProcedure: {1}\n",
                e->Errors->Item[i]->Source, e->Errors->Item[i]->Procedure )
          );
      }

      System::Diagnostics::EventLog* log = new System::Diagnostics::EventLog();
      log->Source = S"My Application";
      log->WriteEntry(errorMessages);
      Console::WriteLine(S"An exception occurred. Please contact your system administrator.");
    }
 }

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Data.SqlClient

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: System.Data (in System.Data.dll)

See Also

SqlException Members | System.Data.SqlClient Namespace | SqlError | SqlErrorCollection

Show:
© 2014 Microsoft