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).
Simple answer NO. You can try and see for yourself. Only if the
IF ..
block evaluates toTRUE
then it will. See a sample code below