- T/SQL Part One
- T/SQL Part Two
- T/SQL Part Three- Stored Procedures and Functions
- T/SQL Part Four-Database Trigger
Exception Handling in SQL Server: Exception Handling is used to handle errors in a program. We handle errors in a program both through the programming language as well as databases. Exception handling provides a proper way to handle an error. In programming, handling error needs to stop the abnormal termination and allows the statement which is not related to the error to execute. In the SQL Server, handling errors means stopping the execution of statements which is related to the error.pasting.error handling in SQL Server and provides more control over T/SQL.
Handle Error In SQL Server
SQL Server in 2005 added the structure of handling error with the help of try and catch blocks which should be used as follows-
- Begin Try
- <statements>
- End Try
- Begin Catch
- <Statements>
- End Catch
Example
Create a procedure for dividing the two variable values using try and catch implementation with user defined error statement?
- create procedure sp_Add
- @a int,@b int
- as
- begin
- declare @c int
- begin try
- set @c=@a/@b
- print 'Divide is'+ cast(@c as char)
- end try
- begin catch
- print 'Diivde By Zero error'
- end catch
- end
- exec sp_add 4,0
- ERROR_MESSAGE()
- ERROR_LINE()
- ERROR_NUMBER()
- ERROR_STATE()
- ERROR_SEVERITY()
- ERROR_PROCEDURE()
ERROR_MESSAGE
It is a predefined method which will be used for displaying the information about the execution which was found in the try block.
- create procedure sp_addone
- @a int,
- @b int
- as
- begin
- declare @c int
- begin try
- set @c=@a/@b;
- print 'Add is:'+cast (@C as char)
- end try
- begin catch
- print error_message()
- end catch
- end


Join the conversation! Your thoughts help the community grow.