Skip to content
Advertisement

Catch block not being executed

A QA tester in my company noticed that the catch block in an insert..exec statement is incorrectly attributing the error to the outer procedure instead of an inner procedure.

The inner procedure is being called in several different places in various stored procedures. It’s working fine, but I was tasked with adding error logging to the inner procedure. We are having the issue where the error is being attributed to the outer procedure. We both think that this is incorrect behavior. Is there a way to get the CATCH block in the inner procedure to work?

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0309ce5d61a4e700b6818d0f132ab2de

Advertisement

Answer

This is an intended behaviour.

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.

Object name resolution errors

These errors are returned to the level that ran the batch, stored procedure, or trigger.

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-ver15#errors-unaffected-by-a-trycatch-construct

If you want to handle missing object error in the [FirstProc] check object existance, raise error in your code.

db<>fiddle

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement