Chapter 7_Handling PLSQL Errors (2)
Chapter 7_Handling PLSQL Errors (2)
Usually, these are generated because of unexpected human input such as passing an unexpected data
type input e.g. passing an integer at the place of a string value, dividing a number by zero, etc.
But in real-life scenarios, the program is not supposed to be broken down, but execute flawlessly.
Therefore, there is a need for a mechanism that can handle the situations that affect the program’s
normal execution or cause it to break. This mechanism is called exception handling or error handling.
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
In the context of Microsoft SQL Server, exceptions are typically managed using the T-SQL TRY...CATCH construct. Here are
some advantages of using SQL Server exceptions:
Error Handling: The primary advantage is proper error handling. The TRY...CATCH block allows you to handle errors in a
controlled and systematic way. This is crucial in preventing unexpected issues from crashing your application.
Structured Error Information: When an exception occurs, the CATCH block provides detailed information about the error.
This includes the error number, severity, state, and error message. This information is valuable for diagnosing and
troubleshooting issues.
Transaction Control: Exception handling is essential for maintaining transactional integrity. If an error occurs within a
transaction, you can roll back the transaction to ensure that the database remains in a consistent state.
Custom Error Messages: You can use the THROW statement within the CATCH block to raise a custom error message. This
allows you to provide more meaningful information to developers or users, making it easier to understand and resolve
issues.
Nested Error Handling: SQL Server allows nested TRY...CATCH blocks. This means you can have an outer block that catches
more generic errors and an inner block that handles specific errors. This provides a hierarchical structure for error handling.
Clean Resource Handling: The CATCH block allows you to perform cleanup operations, such as closing open connections or
releasing resources, before exiting the stored procedure or batch.
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
TRY..CATCH Syntax
BEGIN TRY
--T-SQL statements
--or T-SQL statement blocks
END TRY
BEGIN CATCH
--T-SQL statements
--or T-SQL statement blocks
END CATCH
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
Types of SQL Server Exceptions
SQL Server contains the following two types of exceptions:
1. System Defined
2. User Defined
System Defined Exception
In a System Defined Exception, the system generates exceptions (errors).
Example:
Declare @val1 int;
Declare @val2 int;
BEGIN TRY
Set @val1=8; Output
Set @val2=@val1/0; /* Error Occur Here */ •Error Occur that is:
END TRY •Divide by zero error
BEGIN CATCH encountered
Print 'Error Occur that is:'
Print Error_Message()
END CATCH
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
User Defined Exception
This type of exception is user-generated, not system generated.
Example :
Declare @val1 int;
Declare @val2 int;
BEGIN TRY
Set @val1=8;
Set @val2=@val1%2; Output
if @val1=1 •Error Occur
Print ' Error Not Occur' •Error Occur that is:
else •Number Is Even
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
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
User Defined Exception
This type of exception is user-generated, not system generated.
Syntax:
BEGIN TRY
-- Code that may raise a user-defined exception
IF (SomeCondition)
RAISEERROR('Custom Error Message', 16, 1)
END TRY
BEGIN CATCH
-- Handle the user-defined exception here
END CATCH
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
create PROCEDURE spDivideTwoNumber
@Number1 INT,
@Number2 INT
AS
BEGIN
DECLARE @Result INT
SET @Result = 0
IF(@Number2 = 0)
BEGIN
RAISERROR('Second Number Cannot be zero', 16, 1)
END
ELSE
BEGIN
SET @Result = @Number1 / @Number2
PRINT 'RESULT IS : '+ CAST(@Result AS VARCHAR)
END
END
spDivideTwoNumber 2,0
spDivideTwoNumber 2,1
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
User Defined Exception
This type of exception is user-generated, not system generated.
Example :
Declare @val1 int;
Declare @val2 int;
BEGIN TRY
Set @val1=8;
Set @val2=@val1%2; Output
if @val1=1 •Error Occur
Print ' Error Not Occur' •Error Occur that is:
else •Number Is Even
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
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
Error Functions used within CATCH block
ERROR_NUMBER()
This returns the error number and its value is the same as for @@ERROR function.
ERROR_LINE()
This returns the line number of T-SQL statement that caused an error.
ERROR_SEVERITY()
This returns the severity (the fact or condition of being severe) level of the error.
ERROR_STATE()
This returns the state number of the error.
ERROR_PROCEDURE()
This returns the name of the stored procedure or trigger where the error occurred.
ERROR_MESSAGE()
This returns the full text of error message. The text includes the values supplied for any
substitutable parameters, such as lengths, object names, or times.
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
Exception handling example
BEGIN TRY
DECLARE @num INT, @msg varchar(200)
---- Divide by zero to generate Error
SET @num = 5/0
PRINT 'This will not execute'
END TRY
BEGIN CATCH
PRINT 'Error occured that is'
set @msg=(SELECT ERROR_MESSAGE())
print @msg;
END CATCH
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
Exception handling example
BEGIN TRY
DECLARE @num INT
---- Divide by zero to generate Error
SET @num = 5/0
PRINT 'This will not execute'
END TRY
BEGIN CATCH
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;
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
GOTO
GOTO causes a jump to a specific step or statement. It alters the flow of execution to a label. We
declare some labels in batches and alter we can move to a specific label. GOTO can exist within a
conditional control-of-flow statement, statement blocks, or procedures but cannot go to a label
outside the batch. GOTO cannot be used to jump into a TRY or CATCH scope.
Declare @Var Int;
Set @Var=1
Print 'Goto exercise'
If @Var%2=0
GOTO Label1; Output
else •Goto exercise
GOTO Label2; •Var Is Even
Set @Var=@Var+1;
Label1:
Print 'Var Is Odd'
Label2:
Print 'Var Is Even'
Advance Database using PL/SQL
Unit 7 : Handling PL/SQL Errors
GOTO
GOTO causes a jump to a specific step or statement. It alters the flow of execution to a label. We
declare some labels in batches and alter we can move to a specific label. GOTO can exist within a
conditional control-of-flow statement, statement blocks, or procedures but cannot go to a label
outside the batch. GOTO cannot be used to jump into a TRY or CATCH scope.
Declare @Var Int;
Set @Var=1
Print 'Goto exercise'
If @Var%2=0
GOTO Label1;
else
GOTO Label2;
Set @Var=@Var+1;
Label1:
Print 'Var Is Odd'
Label2:
Print 'Var Is Even'