You are on page 1of 6

Introduction to PL/SQL

(Procedure and Cursor)

Slide 1-1
EXCEPTION-HANDLING SECTION
▪The exception-handling section is the last section of the PL/SQL
block.
▪An exception is a PL/SQL error that is raised during program
execution, either implicitly or explicitly by your program.
▪Handle an exception by trapping it with a handler or propagating it to
the calling environment.
▪There are two categories of exceptions in the world of PL/SQL:
predefined and user-defined.
➢A predefined exception is an internally defined exception that is
assigned a name by PL/SQL.
➢A user-defined exception is one you have declared in the
declaration section of a program unit. User-defined exceptions can
be associated with an internally defined exception (that is, you can
give a name to an otherwise unnamed exception) or with an
application-specific error.
EXCEPTION-HANDLING SECTION
For example, if your SELECT statement returns multiple rows, then
Oracle returns an error (exception) at runtime.
DECLARE
> v_lname VARCHAR2 (15);
> BEGIN
> SELECT last_name INTO v_lname
> FROM employees
> WHERE first_name = 'John';
> DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
> END;
> /
8507: ORA-01422: exact fetch returns more than requested number of
rows

Slide 2-
3
EXCEPTION-HANDLING SECTION
You can handle such exceptions in your PL/SQL block so that your program
completes successfully. For example:
Command> DECLARE
> v_lname VARCHAR2 (15);
> BEGIN
> SELECT last_name INTO v_lname
> FROM employees
> WHERE first_name = 'John';
> DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
> EXCEPTION
> WHEN TOO_MANY_ROWS THEN
> DBMS_OUTPUT.PUT_LINE (' Your SELECT statement retrieved multiple
> rows. Consider using a cursor.');
> END;
Your SELECT statement retrieved multiple rows. Consider using a cursor.
Slide 2-
4
TRAPPING USER-DEFINED EXCEPTIONS
DECLARE

> v_deptno NUMBER := 500;

> v_name VARCHAR2 (20) := 'Testing';

> e_invalid_dept EXCEPTION;

> BEGIN
> UPDATE departments

> SET department_name = v_name

> WHERE department_id = v_deptno;

> IF SQL%NOTFOUND THEN

> RAISE e_invalid_dept;

> END IF;

> ROLLBACK;

> EXCEPTION

> WHEN e_invalid_dept THEN

> DBMS_OUTPUT.PUT_LINE ('No such department');

> DBMS_OUTPUT.PUT_LINE (SQLERRM);

> DBMS_OUTPUT.PUT_LINE (SQLCODE);

> END;

No such department

Slide 2-
5
SOME PREDEFINED EXCEPTIONS
CURSOR_ALREADY_OPEN ORA-06511 6511 Program attempted to open an already
ED opened cursor.

NO_DATA_FOUND ORA-01403 100 Single row SELECT returned no rows or


your program referenced a deleted
element in a nested table or an
uninitialized element in an associative
array (index-by table).

TOO_MANY_ROWS ORA-01422 1422 Single row SELECT returned multiple rows.

ZERO_DIVIDE ORA-01476 1476 A program attempted to divide a number


by zero.

You might also like