THROW (Transact-SQL)THROW (Transact-SQL)

適用於: 是SQL Server (從 2012 開始) 是Azure SQL Database 是Azure SQL 資料倉儲 是平行處理資料倉儲 APPLIES TO: yesSQL Server (starting with 2012) yesAzure SQL Database yesAzure SQL Data Warehouse yesParallel Data Warehouse

SQL Server 2017SQL Server 2017 中引發例外狀況,並將執行轉移至 TRY...CATCH 建構的 CATCH 區塊。Raises an exception and transfers execution to a CATCH block of a TRY...CATCH construct in SQL Server 2017SQL Server 2017.

主題連結圖示 Transact-SQL 語法慣例Topic link icon Transact-SQL Syntax Conventions

語法Syntax

THROW [ { error_number | @local_variable },  
        { message | @local_variable },  
        { state | @local_variable } ]   
[ ; ]  

引數Arguments

error_numbererror_number
這是代表例外狀況的常數或變數。Is a constant or variable that represents the exception. error_numberint,必須大於或等於 50000,並小於或等於 2147483647。error_number is int and must be greater than or equal to 50000 and less than or equal to 2147483647.

messagemessage
這是描述例外狀況的字串或變數。Is an string or variable that describes the exception. messagenvarchar(2048)message is nvarchar(2048).

statestate
這是介於 0 和 255 之間的常數或變數,表示要與訊息相關聯的狀態。Is a constant or variable between 0 and 255 that indicates the state to associate with the message. statetinyintstate is tinyint.

RemarksRemarks

THROW 陳述式之前的陳述式後面必須接著分號 (;) 陳述式結束字元。The statement before the THROW statement must be followed by the semicolon (;) statement terminator.

如果沒有 TRY...CATCH 建構,就會終止陳述式批次。If a TRY...CATCH construct is not available, the statement batch is terminated. 系統會設定引發例外狀況的行號和程序。The line number and procedure where the exception is raised are set. 嚴重性設為 16。The severity is set to 16.

如果指定不含參數的 THROW 陳述式,它必須出現在 CATCH 區塊內。If the THROW statement is specified without parameters, it must appear inside a CATCH block. 這會導致引發攔截到的例外狀況。This causes the caught exception to be raised. THROW 陳述式中發生的任何錯誤都會導致陳述式批次終止。Any error that occurs in a THROW statement causes the statement batch to be terminated.

% 是 THROW 陳述式訊息文字中的保留字元,而且必須逸出。% is a reserved character in the message text of a THROW statement and must be escaped. 重複兩遍 % 字元使 % 返回為訊息文字的一部分,例如 ' 增加超過 15%%的原始值。 'Double the % character to return % as part of the message text, for example 'The increase exceeded 15%% of the original value.'

RAISERROR 和 THROW 之間的差異Differences Between RAISERROR and THROW

下表列出 RAISERROR 和 THROW 陳述式之間的某些差異。The following table lists differences between the RAISERROR and THROW statements.

RAISERROR 陳述式RAISERROR statement THROW 陳述式THROW statement
如果將 msg_id 傳遞給 RAISERROR,則識別碼必須定義在 sys.messages 中。If a msg_id is passed to RAISERROR, the ID must be defined in sys.messages. error_number 參數不需要定義在 sys.messages 中。The error_number parameter does not have to be defined in sys.messages.
msg_str 參數可以包含 printf 格式化樣式。The msg_str parameter can contain printf formatting styles. message 參數不接受 printf 樣式格式。The message parameter does not accept printf style formatting.
severity 參數指定例外狀況的嚴重性。The severity parameter specifies the severity of the exception. 沒有任何 severity 參數。There is no severity parameter. 例外狀況嚴重性永遠設為 16。The exception severity is always set to 16.

範例Examples

A.A. 使用 THROW 來引發例外狀況Using THROW to raise an exception

下列範例示範如何使用 THROW 陳述式引發例外狀況。The following example shows how to use the THROW statement to raise an exception.

THROW 51000, 'The record does not exist.', 1;  

以下為結果集:Here is the result set.

Msg 51000, Level 16, State 1, Line 1  
 
The record does not exist.

B.B. 使用 THROW 來重新引發例外狀況Using THROW to raise an exception again

下列範例示範如何使用 THROW 陳述式,重新引發上次擲回的例外狀況。The following example shows how use the THROW statement to raise the last thrown exception again.

USE tempdb;  
GO  
CREATE TABLE dbo.TestRethrow  
(    ID INT PRIMARY KEY  
);  
BEGIN TRY  
    INSERT dbo.TestRethrow(ID) VALUES(1);  
--  Force error 2627, Violation of PRIMARY KEY constraint to be raised.  
    INSERT dbo.TestRethrow(ID) VALUES(1);  
END TRY  
BEGIN CATCH  
  
    PRINT 'In catch block.';  
    THROW;  
END CATCH;  
  

以下為結果集:Here is the result set.

In catch block. 
Msg 2627, Level 14, State 1, Line 1  
Violation of PRIMARY KEY constraint 'PK__TestReth__3214EC272E3BD7D3'. Cannot insert duplicate key in object 'dbo.TestRethrow'.  
The statement has been terminated.

C.C. 使用 FORMATMESSAGE 搭配 THROWUsing FORMATMESSAGE with THROW

下列範例示範如何使用 FORMATMESSAGE 函數搭配 THROW 來擲回自訂的錯誤訊息。The following example shows how to use the FORMATMESSAGE function with THROW to throw a customized error message. 此範例會先使用 sp_addmessage 來建立使用者定義的錯誤訊息。The example first creates a user-defined error message by using sp_addmessage. 因為 THROW 陳述式不允許在 message 參數中使用替代參數 (而 RAISERROR 允許),所以 FORMATMESSAGE 函式會用來傳遞錯誤訊息 60000 所預期的三個參數值。Because the THROW statement does not allow for substitution parameters in the message parameter in the way that RAISERROR does, the FORMATMESSAGE function is used to pass the three parameter values expected by error message 60000.

EXEC sys.sp_addmessage  
     @msgnum   = 60000  
,@severity = 16  
,@msgtext  = N'This is a test message with one numeric parameter (%d), one string parameter (%s), and another string parameter (%s).'  
    ,@lang = 'us_english';   
GO  
  
DECLARE @msg NVARCHAR(2048) = FORMATMESSAGE(60000, 500, N'First string', N'second string');   
  
THROW 60000, @msg, 1;  
  

以下為結果集:Here is the result set.

Msg 60000, Level 16, State 1, Line 2  
This is a test message with one numeric parameter (500), one string parameter (First string), and another string parameter (second string).

另請參閱See Also

FORMATMESSAGE (Transact-SQL) FORMATMESSAGE (Transact-SQL)
資料庫引擎錯誤嚴重性 Database Engine Error Severities
ERROR_LINE (Transact-SQL) ERROR_LINE (Transact-SQL)
ERROR_MESSAGE (Transact-SQL) ERROR_MESSAGE (Transact-SQL)
ERROR_NUMBER (Transact-SQL) ERROR_NUMBER (Transact-SQL)
ERROR_PROCEDURE (Transact-SQL) ERROR_PROCEDURE (Transact-SQL)
ERROR_SEVERITY (Transact-SQL) ERROR_SEVERITY (Transact-SQL)
ERROR_STATE (Transact-SQL) ERROR_STATE (Transact-SQL)
RAISERROR (Transact-SQL) RAISERROR (Transact-SQL)
@@ERROR (Transact-SQL) @@ERROR (Transact-SQL)
GOTO (Transact-SQL) GOTO (Transact-SQL)
BEGIN...END (Transact-SQL) BEGIN...END (Transact-SQL)
XACT_STATE (Transact-SQL) XACT_STATE (Transact-SQL)
SET XACT_ABORT (Transact-SQL)SET XACT_ABORT (Transact-SQL)