Uredi

Deli z drugimi prek


SqlException Class

Definition

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

public ref class SqlException sealed : System::Data::Common::DbException
public ref class SqlException sealed : SystemException
public sealed class SqlException : System.Data.Common.DbException
[System.Serializable]
public sealed class SqlException : SystemException
[System.Serializable]
public sealed class SqlException : System.Data.Common.DbException
type SqlException = class
    inherit DbException
[<System.Serializable>]
type SqlException = class
    inherit SystemException
[<System.Serializable>]
type SqlException = class
    inherit DbException
Public NotInheritable Class SqlException
Inherits DbException
Public NotInheritable Class SqlException
Inherits SystemException
Inheritance
Inheritance
Inheritance
Attributes

Examples

The following example generates a SqlException and then displays the exception.

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}
Public Sub ShowSqlException(ByVal connectionString As String)
    Dim queryString As String = "EXECUTE NonExistantStoredProcedure"
    Dim errorMessages As New StringBuilder()

    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)

        Try
            command.Connection.Open()
            command.ExecuteNonQuery()

        Catch ex As SqlException
            Dim i As Integer
            For i = 0 To ex.Errors.Count - 1
                errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
                    & "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
                    & "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
                    & "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
                    & "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
            Next i
            Console.WriteLine(errorMessages.ToString())
        End Try
    End Using
End Sub

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 that have 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 ordinarily 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 about the warning and informational messages sent by SQL Server, see Database Engine Events and Errors. The SqlException class maps to SQL Server severity.

The following is general information on handling exceptions. Your code should catch exceptions to prevent the application from crashing and to allow displaying a relevant error message to the user. You can use database transactions to ensure that the data is consistent regardless of what happens in the client application (including a crash). Features like System.Transaction.TransactionScope or the BeginTransaction method (in System.Data.OleDb.OleDbConnection, System.Data.ODBC.ODBCConnection, and System.Data.SqlClient.SqlConnection) ensure consistent data regardless of exceptions raised by a provider. Transactions can fail, so catch failures and retry the transaction.

Note that beginning with .NET Framework 4.5, SqlException can return an inner Win32Exception.

The exception class of a .NET Framework data provider reports provider-specific errors. For example System.Data.Odbc has OdbcException, System.Data.OleDb has OleDbException, and System.Data.SqlClient has SqlException. For the best level of error detail, catch these exceptions and use the members of these exception classes to get details of the error.

In addition to the provider-specific errors, .NET Framework data provider types can raise .NET Framework exceptions such as System.OutOfMemoryException and System.Threading.ThreadAbortException. Recovery from these exceptions may not be possible.

Bad input can cause a .NET Framework data provider type to raise an exception such as System.ArgumentException or System.IndexOutOfRangeException. Calling a method at the wrong time can raise System.InvalidOperationException.

So, in general, write an exception handler that catches any provider specific exceptions as well as exceptions from the common language runtime. These can be layered as follows:

try {  
   // code here  
}  
catch (SqlException odbcEx) {  
   // Handle more specific SqlException exception here.  
}  
catch (Exception ex) {  
   // Handle generic ones here.  
}  

Or:

try {  
   // code here  
}  
catch (Exception ex) {  
   if (ex is SqlException) {  
      // Handle more specific SqlException exception here.  
   }  
   else {  
      // Handle generic ones here.  
   }  
}  

It is also possible for a .NET Framework data provider method call to fail on a thread pool thread with no user code on the stack. In this case, and when using asynchronous method calls, you must register the UnhandledException event to handle those exceptions and avoid application crash.

Properties

BatchCommand

If this DbException was thrown when executing a DbBatch, references the specific DbBatchCommand which triggered the exception.

(Inherited from DbException)
Class

Gets the severity level of the error returned from the .NET Framework Data Provider for SQL Server.

ClientConnectionId

Represents the client connection ID. For more information, see Data Tracing in ADO.NET.

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
DbBatchCommand

When overridden in a derived class, if this DbException was thrown when executing a DbBatch, references the specific DbBatchCommand which triggered the exception.

(Inherited from DbException)
ErrorCode

Gets the HRESULT of the error.

(Inherited from ExternalException)
Errors

Gets a collection of one or more SqlError objects that give detailed information about exceptions generated by the .NET Framework Data Provider for SQL Server.

HelpLink

Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException

Gets the Exception instance that caused the current exception.

(Inherited from Exception)
IsTransient

Indicates whether the error represented by this DbException could be a transient error, i.e. if retrying the triggering operation may succeed without any other change.

(Inherited from DbException)
LineNumber

Gets the line number within the Transact-SQL command batch or stored procedure that generated the error.

Message

Gets the text describing the error.

Message

Gets a message that describes the current exception.

(Inherited from Exception)
Number

Gets a number that identifies the type of error.

Procedure

Gets the name of the stored procedure or remote procedure call (RPC) that generated the error.

Server

Gets the name of the computer that is running an instance of SQL Server that generated the error.

Source

Gets the name of the provider that generated the error.

SqlState

For database providers which support it, contains a standard SQL 5-character return code indicating the success or failure of the database operation. The first 2 characters represent the class of the return code (e.g. error, success), while the last 3 characters represent the subclass, allowing detection of error scenarios in a database-portable way.

For database providers which don't support it, or for inapplicable error scenarios, contains null.

(Inherited from DbException)
StackTrace

Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
State

Gets a numeric error code from SQL Server that represents an error, warning or "no data found" message. For more information about how to decode these values, see Database Engine Events and Errors.

TargetSite

Gets the method that throws the current exception.

(Inherited from Exception)

Methods

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

Sets the SerializationInfo with information about the exception.

GetObjectData(SerializationInfo, StreamingContext)
Obsolete.

When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType()

Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current SqlException object, and includes the client connection ID (for more information, see ClientConnectionId).

ToString()

Returns a string that contains the HRESULT of the error.

(Inherited from ExternalException)
ToString()

Creates and returns a string representation of the current exception.

(Inherited from Exception)

Events

SerializeObjectState
Obsolete.

Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Applies to

See also