1

We are handling Exceptions in our stored procedures using Try/Catch block. In a stored procedure I have intentionally made an error to check how the exceptions being handled. I wrote a stored procedure like as below,

CREATE PROCEDURE TEST
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
    BEGIN TRAN
        
              ;WITH CTE
              AS
              (SELECT TOP 10 * 
               FROM student)

               SELECT * FROM CTE

               SELECT * INTO #VAL
               FROM CTE

   
      IF @@ERROR = 0
              BEGIN
                  COMMIT TRAN;
              END
      END TRY
      BEGIN CATCH
              SELECT @@ERROR AS ERROR, ERROR_LINE() AS [Error Line], ERROR_MESSAGE() AS [Error Message] 
      ROLLBACK TRAN;
      END CATCH
SET NOCOUNT OFF;
END

In the Above Stored procedure I have used a CTE multiple Times. I expected that SQL-SERVER will handle the exception but it didn't. While Executing the Above stored Procedure I got below error

Msg 208, Level 16, State 1, Procedure TEST, Line 16

Invalid object name 'CTE'.

Msg 266, Level 16, State 2, Procedure TEST, Line 16

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.

Why the Exception is not handled ? Could someone give idea on this?

Thanks for the help.

0

1 Answer 1

2

stored procedures follow deferred object name resolution while executing.So in this case cte is a non existent object to it .

Further try catch cannot handle this type of errors

The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:

Compile errors, such as syntax errors, that prevent a batch from running.


Errors that occur during statement-level recompilation, such as **object name resolution errors** that occur after compilation because of deferred name resolution

Please see MSDN for more info(see errors unaffected by try catch )

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for teaching me and the msdn link was really helpful :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.