0% found this document useful (0 votes)
8 views

PLSQL Eception Handling

Uploaded by

umang kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PLSQL Eception Handling

Uploaded by

umang kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Understanding Exception

Handling
Arshad Madanii
Associate Software Developer
Vibhathi Labs Ind Pvt Ltd

06/05/2024 SQL BASICS 1


What is an Exception?

An exception is a runtime error or warning condition in a PL/SQL block.

Causes:

Can be caused by user errors, hardware failures, or software errors.


Types: System-defined exceptions and user-defined exceptions.

You cannot anticipate all possible


exceptions, but you can write
exception handlers that let your
program to continue to operate in
their presence

06/10/2024 SQL BASICS 3


Exception :
Any PL/SQL block can have an
• Internally defined exception-handling part, which can
have one or more exception handlers
• Predefined
• User-defined

Internally defined:

The runtime system raises internally defined


exceptions implicitly (automatically). Examples of
internally defined exceptions are ORA-00060
(deadlock detected while waiting for resource) and
ORA-27102 (out of memory).

An internally defined exception always has an


error code but does not have a name unless
PL/SQL gives it one or you give it one.

06/10/2024 SQL BASICS 4


Predefined

A predefined exception is an internally defined exception that PL/SQL


has given a name. For example, ORA-06500 (PL/SQL: storage error) has
the predefined name STORAGE_ERROR.

User-defined

You can declare your own exceptions in the declarative part of


any PL/SQL anonymous block, subprogram, or package. For
example, you might declare an exception named
insufficient_funds to flag overdrawn bank accounts.

06/10/2024 SQL BASICS 5


Has Error Raised
Category Definer Code Has Name Implicitly Raised Explicitly
Internally Runtime system Always Only if you Yes OptionallyFoot 1
defined assign one

Predefined Runtime system Always Always Yes OptionallyFoot 1

User-defined User Only if you Always No Always


assign one

06/10/2024 SQL BASICS 6


Common Exceptions:

Examples:

NO_DATA_FOUND : Raised when a SELECT INTO statement returns no rows.

TOO_MANY_ROWS : Raised when a SELECT INTO statement returns more than


one row.

ZERO_DIVIDE : Raised when an attempt is made to divide a number by


zero.

VALUE_ERROR : Raised when an arithmetic, conversion, truncation, or size-


constraint error occurs.

06/10/2024 SQL BASICS 7


Handling Predefined Exceptions:

Syntax:

BEGIN
-- PL/SQL block
EXCEPTION
WHEN exception_name THEN
-- Exception handling code
END;

Example:

BEGIN
SELECT salary INTO v_salary FROM employees WHERE employee_id = 100;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID 100');
END;

06/10/2024 SQL BASICS 8


Handling User-Defined Exceptions:

1.Steps: Declare the exception.


2.Raise the exception using RAISE statement.
3.Handle the exception in the EXCEPTION section.
DECLARE
Syntax: e_insufficient_balance EXCEPTION;
v_balance NUMBER := 500;
DECLARE v_withdrawal NUMBER := 1000;
e_custom EXCEPTION; BEGIN
BEGIN IF v_withdrawal > v_balance THEN
-- Condition that causes exception RAISE e_insufficient_balance;
RAISE e_custom; END IF;
EXCEPTION EXCEPTION
WHEN e_custom THEN WHEN e_insufficient_balance THEN
-- Exception handling code
END; DBMS_OUTPUT.PUT_LINE('Insufficient
balance for withdrawal');
END;

06/10/2024 SQL BASICS 9


SQLCODE vs SQLERRM

SQLCODE:
Returns the numeric code of the most recent exception.
Syntax: SQLCODE

SQLERRM:
Returns the error message associated with the most recent exception.
Syntax: SQLERRM

Example:

BEGIN
-- Intentional error
SELECT salary INTO v_salary FROM employees WHERE employee_id = -1;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error message: ' || SQLERRM);
END;

06/10/2024 SQL BASICS 10


Pragma EXCEPTION_INIT

Associates an exception with an Oracle error number.

Syntax:
PRAGMA EXCEPTION_INIT(exception_name, error_number);

Example:

DECLARE
e_custom EXCEPTION;
PRAGMA EXCEPTION_INIT(e_custom, -20001);
BEGIN
-- Simulate an Oracle error
RAISE_APPLICATION_ERROR(-20001, 'Custom error message');
EXCEPTION
WHEN e_custom THEN
DBMS_OUTPUT.PUT_LINE('Caught custom exception: ' || SQLERRM);
END;

06/10/2024 SQL BASICS 11


RAISE_APPLICATION_ERROR

The procedure raise_application_error allows you to issue a user-defined error from


a code block or stored program.

By using this procedure, you can report errors to the callers instead of returning
unhandled exceptions.

The raise_application_error has the following syntax:

raise_application_error( In this syntax:


error_number,
message • The error_number is a negative integer with the range from -
[, {TRUE | FALSE}] 20999 to -20000.
); • The message is a character string that represents the error
message. Its length is up to 2048 bytes.
• If the third parameter is FALSE, the error replaces all
previous errors. If it is TRUE, the error is added to the stack
of previous errors.

06/10/2024 SQL BASICS 12


DECLARE
credit_limit_exceed EXCEPTION;
PRAGMA exception_init(credit_limit_exceed, -20111);
l_customer_id customers.customer_id%TYPE := &customer_id;
l_credit_limit customers.credit_limit%TYPE := &credit_limit;
l_customer_credit customers.credit_limit%TYPE;
BEGIN
-- get customer credit limit
SELECT credit_limit INTO l_customer_credit
FROM customers
WHERE customer_id = l_customer_id;
-- raise an exception if the credit limit is exceeded
IF l_customer_credit > l_credit_limit THEN
raise_application_error(-20111,'Credit Limit Exceeded');
END IF;
dbms_output.put_line('Credit Limit is checked and passed’);
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Customer with id ' || l_customer_id || ' does not exist.');
END;
/

06/10/2024 SQL BASICS 13


Advantages:
Simplifies Programming:
Improves Maintainability:
Exception handlers make programs easier to write
and understand by centralizing error-handling code Error-handling code is isolated within exception-handling
in designated parts of the program. parts of the blocks, making it easier to maintain and update
in the future.
Reduces Code Complexity:
Enhances Readability:
Without exception handlers, developers would need
to manually check for every possible error at By encapsulating error-handling logic within exception
various points in the code, leading to scattered handlers, code readability improves as developers can
error-handling logic throughout the program. focus on the main logic of the program without being
distracted by error-handling details.
Mitigates Oversight:
Facilitates Debugging:
Exception handlers reduce the likelihood of
overlooking potential errors since developers don't When an error occurs, exception handlers provide a
need to anticipate every possible error scenario structured way to handle it, making it easier to identify and
explicitly. debug issues in the codebase
.0 6 / 1 0 / 2 0 2 4 SQL BASICS 14
Scope rule(limitations):
Visibility: Errors raised with RAISE_APPLICATION_ERROR are visible only
within the current PL/SQL block or subprogram.

Error Number Range: Custom error numbers should fall within the range of -
20000 to -20999.

Error Message Length: The custom error message should not exceed 2048
bytes.

Security: Avoid exposing sensitive information through error messages to


prevent security vulnerabilities.

06/10/2024 SQL BASICS 15


DBMS_UTILITY.FORMAT_CALL_STACK:

This function formats the current call stack (sequence of procedure calls) as a
string. It's often used in exception handling to log or display the sequence of
procedure calls that led to the current point in the code. This can be very helpful
for debugging and tracing the flow of execution in a PL/SQL program.

DBMS_UTILITY.FORMAT_ERROR_BACKTRACE:

This function formats the error backtrace (sequence of procedure calls) for the
most recent error on the stack. It's often used in exception handling to log or
display the full error stack, including the line numbers and positions of the errors.

06/10/2024 SQL BASICS 16


Best Practices for Exception Handling

Guidelines:

• Always handle exceptions to prevent runtime errors.


• Use specific exceptions instead of OTHERS to make debugging easier.
• Log errors using DBMS_OUTPUT or a logging table.
• Avoid excessive use of exceptions for flow control.

06/10/2024 SQL BASICS 17


Next Session
Creation of Stored Procedures – 03 June 2024

06/10/2024 SQL BASICS 18


Thank you

06/10/2024 SQL BASICS 19

You might also like