重新丟擲 RAISERROR 生成的異常

你可以使用 TRHOW 語句重新丟擲在 CATCH 塊中捕獲的錯誤:

DECLARE @msg nvarchar(50) = 'Here is a problem! Area: ''%s'' Line:''%i'''
BEGIN TRY
    print 'First statement';
    RAISERROR(@msg, 11, 1, 'TRY BLOCK', 2);
    print 'Second statement';
END TRY
BEGIN CATCH
    print 'Error: ' + ERROR_MESSAGE();
    THROW;
END CATCH

請注意,在這種情況下,我們使用格式化引數(第四個和第五個引數)引發錯誤。如果要在訊息中新增更多資訊,這可能很有用。執行結果是:

First statement
Error: Here is a problem! Area: 'TRY BLOCK' Line:'2'
Msg 50000, Level 11, State 1, Line 26
Here is a problem! Area: 'TRY BLOCK' Line:'2'