TSQL 2005 try-catch block

In this TSQL code, assume that the correct name of "col1" is "date_col"
declare @date_var datetime
begin try
    select @date_var = max(col1) from table1
end try
begin catch
    select 'my error!!!'
end catch

This code returns the error message:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'col1'.

and it does NOT display "my error!!!".

I had assumed that after finding the error in the try block, the catch block would execute and I would see the text "my error!!!". But it appears that the catch block is not being executed. What is wrong with my understanding?

Who is Participating?
According to Microsoft:

A TRY&CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection.

Your exception does not qualify since it's more of a compilation error than an error that happens during execution.

You must get past simple syntax errors before that will work
Try changing your code to
select @date_var = someVarcharColumnNameWithDataInIt from TableThatExists

and you'll get your error because it can't cast a string that isn't a date to a datetime type.
Try this in the catch:
Select null Errornbr, null Severity, null ErrorLine, 'my error!!!' Msg
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.