Exception Handling in SQL Server
SQL Server provides TRY, CATCH blocks for exception handling.
BEGIN TRY
/* T-SQL Statements */
END TRY
BEGIN CATCH
- Print Error OR
- Rollback Transaction
END CATCH
/* T-SQL Statements */
END TRY
BEGIN CATCH
- Print Error OR
- Rollback Transaction
END CATCH
Types of Exceptions
SQL Server contains the following two types of exceptions:
1- System Defined
2- User Defined
2- User Defined
System Defined Exception
In a System Defined Exception the exceptions (errors) are generated by the system.
- Declare @val1 int;
- Declare @val2 int;
- BEGIN TRY
- Set @val1=8;
- Set @val2=@val1/0; /* Error Occur Here */
- END TRY
- BEGIN CATCH
- Print 'Error Occur that is:'
- Print Error_Message()
- END CATCH
Output
Error Occur that is:
Divide by zero error encountered
User Defined Exception
This type of exception is user generated, not system generated.
- Declare @val1 int;
- Declare @val2 int;
- BEGIN TRY
- Set @val1=8;
- Set @val2=@val1%2;
- if @val1=1
- Print ' Error Not Occur'
- else
- Begin
- Print 'Error Occur';
- Throw 60000,'Number Is Even',5
- End
- END TRY
- BEGIN CATCH
- Print 'Error Occur that is:'
- Print Error_Message()
- END CATCH
Output
Error Occur
Error Occur that is:
Number Is Even
Here 60000 denotes the error number and 5 denotes the state to associate with the message.
The following are system functions and the keyword used within a catch block:
@@ERROR
ERROR_NUMBER()
ERROR_STATE()
ERROR_LINE()
ERROR_MESSAGE()
ERROR_PROCEDURE()
ERROR_SEVERITY()
RAISERROR()
GOTO()
0 comments:
Post a Comment