Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Try catch Error ? How

Author  Topic 

jooorj
Posting Yak Master

126 Posts

Posted - 2011-04-13 : 18:52:22
why catch does not fired in this case :

begin try
select * from #tmp -- temp table
end try

begin catch
select 'this is error' as Err
end catch

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-04-13 : 19:07:02
Are we to infer that the table #tmp does not exist? If so, then that is a Compile/parsing error and not a Run-time error.

Maybe this will help?
http://msdn.microsoft.com/en-us/library/ms175976.aspx

Here is a relavent quote from BOL:
quote:
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.


Go to Top of Page

jooorj
Posting Yak Master

126 Posts

Posted - 2011-04-13 : 19:17:46
ok, good
thank you Lamprey
but how can I catch it then, what is the solution of this type of errors ?
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-04-13 : 19:40:08
You can't catch it. You can write good code / program defensivly. Here is one way to not generate an error, but the correct solution depends on what you want to have happen:
begin try 
IF OBJECT_ID('TempDB..#tmp','U') IS NOT NULL
select * from #tmp -- temp table
end try

begin catch
select 'this is error' as Err
end catch
Go to Top of Page

jooorj
Posting Yak Master

126 Posts

Posted - 2011-04-14 : 21:30:13
thanx
that is very clear
Go to Top of Page
   

- Advertisement -