Wrapping a try/catch block in an If statement

5.2k views Asked by At

In T-SQL, the following are true:

  • Try and Catch blocks are considered separate statements
  • An unsuccessful If statement results in the proceeding statement being skipped

Given these facts, will any unusual behavior result from the following code?

IF EXISTS (
    SELECT someValue FROM someTable WHERE someValue = 1
)
BEGIN TRY
    -- do something
END TRY
BEGIN CATCH
    PRINT @@ERROR
END CATCH

Will the PRINT @@ERROR line execute if the IF statement evaluates to false? My hunch is that the code within the Catch block will not be executed if control never reaches the Try block, but I cannot find any documentation to addresses this specific issue.

I could skip over this entire issue by wrapping the entire Try/Catch block in a BEGIN statement, but I'd like to avoid that if possible (just for aesthetics).

1

There are 1 answers

0
Rahul On BEST ANSWER

Will the PRINT @@ERROR line execute if the IF statement evaluates to false?

Simple answer NO. You can try and see for yourself. Only if the IF .. block evaluates to TRUE then it will. See a sample code below

alter procedure testsp
as
begin
declare @var int;

IF EXISTS (
    SELECT Name FROM student WHERE Marks < 90
)
BEGIN TRY
   set @var = 20/0;
END TRY
BEGIN CATCH
    PRINT @@ERROR
END CATCH
end