Common mistake using try/catch constructs

As per BOL, A TRY…CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection. This is a common thing which a developer ignores and get into a trap. Let’s try to understand with an example code.
Here is a sample code, where exception raised by select statement executed in try block will never be caught by catch block:


create table test_tbl
 (id int);
go

begin try
 select *
 from test_t; -- mistakenly typed wrong table name
end try

begin catch
 print 'In catch block - exception handled!';
end catch

-- #Output
-- Msg 208, Level 16, State 1, Line 2
-- Invalid object name 'test_t'.

Here is another example, showing the correct usage of try/catch construct – using divide-by-zero error.

begin try
    select 1/0; -- divide by zero error
end try

begin catch
    print 'In catch block - exception handled!';
end catch 

-- #Output
-- (0 row(s) affected)
-- In catch block - exception handled!

 

Please refer below link for more details:  Books On-Line

Happy Learning!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s