Get startedGet started for free

Nesting TRY...CATCH constructs

You want to register a new buyer in your buyers table. This new buyer is Peter Thomson. His e-mail is [email protected] and his phone number is 555000100.

In your database, there is also a table called errors, in which each error is stored.

You prepare a script that controls possible errors in the insertion of this person's data. It also inserts those errors into the errors table.

How do you prepare the script?

This exercise is part of the course

Transactions and Error Handling in SQL Server

View Course

Exercise instructions

  • Surround the INSERT INTO buyers statement with a TRY block.
  • Surround the error handling with a CATCH block.
  • Surround the INSERT INTO errors statement with another TRY block.
  • Surround the nested error handling with another CATCH block.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

-- Set up the first TRY block
___ ___
	INSERT INTO buyers (first_name, last_name, email, phone)
		VALUES ('Peter', 'Thompson', '[email protected]', '555000100');
___ ___
-- Set up the first CATCH block
___ ___
	SELECT 'An error occurred inserting the buyer! You are in the first CATCH block';
    -- Set up the nested TRY block
    ___ ___
    	INSERT INTO errors 
        	VALUES ('Error inserting a buyer');
        SELECT 'Error inserted correctly!';
	___ ___
    -- Set up the nested CATCH block
    ___ ___
    	SELECT 'An error occurred inserting the error! You are in the nested CATCH block';
    ___ ___ 
___ ___
Edit and Run Code