SqlException 類別

定義

當 SQL Server 傳回警告或錯誤時,所擲回的例外狀況。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
[System.Serializable]
public sealed class SqlException : System.Data.Common.DbException
type SqlException = class
    inherit DbException
Public NotInheritable Class SqlException
Inherits DbException
繼承
屬性

範例

下列範例會產生SqlException , 然後顯示例外狀況。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

備註

每當 SQL Server 的 .NET Framework Data Provider 遇到從伺服器產生的錯誤時, 就會建立此類別。This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (用戶端錯誤會擲回為標準的 common language runtime 例外狀況)。一律包含至少一個的SqlError實例。 SqlException(Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError.

嚴重性層級為10或以下的訊息為資訊, 並指出使用者已輸入的資訊中的錯誤所造成的問題。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. 從11到16的嚴重性層級是由使用者所產生, 並可由使用者加以更正。Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. 17 到 25 的嚴重性層級表示軟體或硬體錯誤。Severity levels from 17 through 25 indicate software or hardware errors. 當層級17、18或19發生錯誤時, 您可以繼續工作, 但您可能無法執行特定語句。When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.

當嚴重性層級為 19 或低於 19 時,SqlConnection 仍保持開啟。The SqlConnection remains open when the severity level is 19 or less. 當嚴重性層級為20或更大時, 伺服器通常會SqlConnection關閉。When the severity level is 20 or greater, the server ordinarily closes the SqlConnection. 但是,使用者可以再次開啟連線,然後繼續進行。However, the user can reopen the connection and continue. 在這兩個情況中,SqlException 皆由執行該命令的方法所產生。In both cases, a SqlException is generated by the method executing the command.

如需 SQL Server 所傳送之警告和參考用訊息的詳細資訊, 請參閱資料庫引擎事件和錯誤For information about the warning and informational messages sent by SQL Server, see Database Engine Events and Errors. SqlException類別會對應至 SQL Server 嚴重性。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). BeginTransaction 方法 (OleDbConnection、ODBCConnection 和 system.string) 等功能會確保一致的資料, 不論是否有例外狀況都是一樣的: 不受任何限制由提供者引發。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. 交易可能會失敗, 因此 catch 失敗, 然後重試交易。Transactions can fail, so catch failures and retry the transaction.

請注意, 從 .NET Framework 4.5 開始SqlException , 可以傳回內部Win32ExceptionNote that beginning with .NET Framework 4.5, SqlException can return an inner Win32Exception.

.NET Framework Data Provider 的例外狀況類別會報告提供者特定的錯誤。The exception class of a .NET Framework data provider reports provider-specific errors. 例如, System.data.odbc.odbcexception, system.string 具有 System.data.oledb.oledbexception, 而 SqlClient 有 SqlException 的的資料 (data)。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.

除了提供者特定的錯誤之外, .NET Framework Data Provider 類型也可以引發 .NET Framework 例外狀況, 例如 OutOfMemoryException 和 ThreadAbortException。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.

不正確的輸入可能會導致 .NET Framework Data Provider 類型引發例外狀況, 例如 ArgumentException 或 IndexOutOfRangeException。Bad input can cause a .NET Framework data provider type to raise an exception such as System.ArgumentException or System.IndexOutOfRangeException. 在錯誤的時間呼叫方法, 可能會引發 InvalidOperationException。Calling a method at the wrong time can raise System.InvalidOperationException.

因此, 一般而言, 撰寫的例外狀況處理常式會攔截任何提供者特定的例外, 以及 common language runtime 的例外狀況。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.  
   }  
}  
  

線上程集區執行緒上, 如果堆疊上沒有使用者程式碼, .NET Framework Data Provider 方法呼叫也可能失敗。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. 在此情況下, 以及使用非同步方法呼叫時, 您必須註冊UnhandledException事件以處理這些例外狀況, 並避免應用程式損毀。In this case, and when using asynchronous method calls, you must register the UnhandledException event to handle those exceptions and avoid application crash.

屬性

Class

取得從 .NET Framework Data Provider for SQL Server 傳回的錯誤之嚴重性層級。Gets the severity level of the error returned from the .NET Framework Data Provider for SQL Server.

ClientConnectionId

表示用戶端連接 ID。Represents the client connection ID. 如需詳細資訊,請參閱 ADO.NET 中的資料追蹤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.

(繼承來源 Exception)
Errors

取得一個或多個 SqlError 物件的集合,這些物件可提供有關 .NET Framework Data Provider for SQL Server 產生的例外狀況之詳細資訊。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.

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(繼承來源 Exception)
LineNumber

取得 Transact-SQL 命令批次內的行號或產生錯誤的預存程序 (Stored Procedure)。Gets the line number within the Transact-SQL command batch or stored procedure that generated the error.

Message

取得描述錯誤的文字。Gets the text describing the error.

Number

取得識別錯誤類型的值。Gets a number that identifies the type of error.

Procedure

取得產生錯誤之預存程序或遠端程序呼叫 (RPC) 的名稱。Gets the name of the stored procedure or remote procedure call (RPC) that generated the error.

Server

取得執行 SQL 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.

StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(繼承來源 Exception)
State

從 SQL Server 取得表示錯誤、警告或「找不到資料」訊息的數值錯誤碼。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.

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(繼承來源 Exception)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

使用例外狀況的相關資訊來設定 SerializationInfoSets the SerializationInfo with information about the exception.

GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(繼承來源 Exception)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回字串,代表目前的SqlException物件,並包含用戶端連線識別碼 (如需詳細資訊,請參閱ClientConnectionId)。Returns a string that represents the current SqlException object, and includes the client connection ID (for more information, see ClientConnectionId).

事件

SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(繼承來源 Exception)

適用於

另請參閱