SQL SERVER TRY..CATCH

In SQL Server 2000, Exception was handle by the @@error variable where after each statement SQL Server sets @@error to “0” if the statement was successful, and if not then it will filled by the error number.

you can also use RAISEERROR() function to raise custom erorr when you needed. There was no mechanism such as Exception TRY.. CATCH block in SQL 2000. After each statement you have to check the @@error Variable and then raise an error.

From SQL 2005, errors can be handled in T-SQL same way as C# or any .net programming language by TRY..CATCH block.

syntex:

BEING TRY
{sql_statement| statement block}
END TRY
BEGIN CATCH
{sql_statement| statement block}
END CATCH

A TRY block must be immediately followed by an associated CATCH block. Including any other statements between the END TRY and BEGIN CATCH statements generates a syntax error.

A TRY…CATCH construct cannot span multiple batches. A TRY…CATCH construct cannot span multiple blocks of Transact-SQL statements. For example, a TRY…CATCH construct cannot span two BEGIN…END blocks of Transact-SQL statements and cannot span an IF…ELSE construct.

In the scope of a CATCH block, the following system functions can be used to obtain information about the error that caused the CATCH block to be executed:

* ERROR_NUMBER() returns the number of the error.
* ERROR_SEVERITY() returns the severity.
* ERROR_STATE() returns the error state number.
* ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
* ERROR_LINE() returns the line number inside the routine that caused the error.
* ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

for more information..
Use TRY.. CATCH in transaction

BEGIN TRANSACTION
BEGIN TRY
--
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;

IF @@TRANCOUNR > 0
ROLLBACK TRANSACTION
END CATCH;
IF @@TRANSCOUNT > 0
COMMIT TRANSACTION;
TO

For More information..(More)

Advertisements