Query with a Nested error handling

I am currently reading the book SQL Server 2012 T-SQL Recipes and I have a query regarding Page 455 (20-5. Nested error handling).

The book contains the following code:

BEGIN TRY

                PRINT Outer Try

                                BEGIN TRY

                                                SELECT 1/0

                                END TRY

                BEGIN CATCH

                                PRINT CONVERT (CHAR(5), ERROR_NUMBER())+Inner catch

                END CATCH

END TRY

BEGIN CATCH

                PRINT CONVERT(CHAR(5), ERROR_NUMBER()) + Outer Catch

END CATCH

GO

The results are

Outer Try

(0 row(s) affected)

8134 Inner Catch

The book then states that a nested try catch will work in the following order

  1.        Outer Try block
  2.        Outer Catch block if an error occurs
  3.        Inner Try block
  4.        Outer Catch if an error occurs

Is this correct?  I would expect step 4 to show 4. Inner Catch if an error occurs.  In the example above, the Inner catch is run after the Inner Try block returns an error.


September 7th, 2015 10:45am

I would say this is an error in the book. If there is an error in the inner try it will throw the inner catch as you have shown above. And if there is an error in the outer try it will throw the outer catch, like this:

BEGIN TRY
	PRINT 'Outer Try'
	SELECT 1/0
        
	BEGIN TRY
        SELECT 1/0
    END TRY
    BEGIN CATCH
        PRINT CONVERT (CHAR(5), ERROR_NUMBER())+'Inner catch'
    END CATCH

END TRY
BEGIN CATCH
    PRINT CONVERT(CHAR(5), ERROR_NUMBER()) + 'Outer Catch'
END CATCH
GO

Results:

Outer Try

(0 row(s) affected)

8134 Outer Catch

Unfortunately technical books are often full of coding mistakes. Often times the publisher will release corrections for the code on their website. You can download the source code for the book here:  http://www.apress.com/9781430242000?gtmf=s     Maybe that will have the corrections?

Free Windows Admin Tool Kit Click here and download it now
September 7th, 2015 11:29am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics