Catch fails in Stored Procedure when failure is induced on purpose.
I am trying to test the catch portion in my Stored Procedure by changing a column name after I create the stored procedure. But the catch never gets executed and it fails at the line where the error is. Any ideas on what I could be doing wrong?
Steps to reproduce:
* Create Table ErrorTest
CREATE TABLE [dbo].[ErrorTest](
[ErrorTest] [varchar](50) NULL
) ON [PRIMARY]
* Create Stored Procedure TestError
SET NOCOUNT ON;
DECLARE @EmailMessage AS VARCHAR(5000)
BEGIN
BEGIN TRY
SELECT ErrorTest FROM ErrorTest
END TRY
BEGIN CATCH
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER()
, @message = ERROR_MESSAGE()
, @xstate = XACT_STATE();
SET @EmailMessage = 'Failure ' + CHAR(13) + 'Error Code: '+ CAST(@error AS VARCHAR) + CHAR(13) + @message
EXEC [leads].[usp_SendEmail]
@Mysubject = N'FAILURE!',
@Mybody = @EmailMessage,
@Myrecipients = N'me@email.com'
END CATCH
END
-
Change the name of the column in step 1 from
[ErrorTest] to [ErrorTest2] -
This will make the stored procedure fail with error
Msg 207, Level 16, State 1, Procedure TestError, Line 8
Invalid column name ‘ErrorTest’. -
The catch never gets executed.
The SP is never executes – it simply not compiles – thus there is nothing to execute
Rewrite your TRY section in a way like this and try once more: