Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 682
  • Last Modified:

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?

2 Solutions
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
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.


Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now