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.
- BEGIN TRY
- DECLARE @number INT
-
- SET @number = 2/0
-
- PRINT 'This will not execute'
- END TRY
- BEGIN CATCH
- SELECT ERROR_NUMBER() AS ErrorNumber,
- ERROR_SEVERITY() AS ErrorSeverity,
- ERROR_STATE() AS ErrorState,
- ERROR_MESSAGE() AS ErrorMessage;
- END CATCH;
- GO
When we run this script we get the following output.