How to Handle Errors in SQL Server

We use try catch blocks just like C#. In this example we will try to divide a number by Zero and let us see how the error message is displayed. When the error comes it goes to catch block.

Write the below script in SQL Server.

  1. BEGIN TRY  
  2. DECLARE @number INT  
  3.   
  4. SET @number = 2/0  
  5.   
  6. PRINT 'This will not execute'  
  7. END TRY  
  8. BEGIN CATCH  
  9. SELECT ERROR_NUMBER() AS ErrorNumber,  
  10.    ERROR_SEVERITY() AS ErrorSeverity,  
  11.    ERROR_STATE() AS ErrorState,  
  12.    ERROR_MESSAGE() AS ErrorMessage;  
  13. END CATCH;  
  14. GO  

When we run this script we get the following output.

result