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

Exception

The document discusses exception handling in PL/SQL including defining, raising, and trapping exceptions. It provides examples of implicit and explicit exception raising as well as predefined exceptions and user defined exceptions.

Uploaded by

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

Exception

The document discusses exception handling in PL/SQL including defining, raising, and trapping exceptions. It provides examples of implicit and explicit exception raising as well as predefined exceptions and user defined exceptions.

Uploaded by

ajithram275
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

NAME: SAIKUMAR KUPPUSAMY

DTTM: 20-APR-16 06.36.09.353000 PM +05:30

EXCEPTION
Exception means departure from expected result.
Any error or problem which handled and continues to work normally.

Exception can be defined as the state of an entity, which is different from its conventional and normal
behavior. In context to programming language, exception refers to the abnormal situation in the normal
flow of the program. Oracle server raises exception whenever it encounters a logical violation of the flow
during program execution.

I have listed the common situations which end up raising exceptions and subsequently termination of the
program.

 Design Faults and illogical flow

 Exception propagation from referenced program unit

 Coding mistakes

 Hardware failures

Exception Propagation in a Program Unit

The figure below shows the program flow, which is followed when an exception situation occurs in the
PL/SQL block and the exception has been handled. Once the exception has been raised and trapped, and
the control moves to EXCEPTION section, the program propagates in the forward direction.

If the exception has not been handled, the program terminates abruptly or propagates to the calling
environment
Exception Handling

Exceptions can be trapped in the EXCEPTION section of a PL/SQL block. Oracle supports two ways to
raise exception in a program, implicitly or explicitly.

Exceptions which are automatically raised by the oracle server fall under the category of implicit way
raising an exception. PL/SQL runtime engine identifies the abnormal flow and raises the exception. For
example, NO_DATA_FOUND or TOO_MANY_ROWS are the system defined exceptions which are
raised by the server during program execution.

Exceptions which are trapped in executable section and handled in the EXCEPTION block by the
programmer are explicit ways raising exceptions. In this category, a user can either explicitly raise an
already existing system defined exception or create a new exception and invoke in the program.

SYNTAX
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
...
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
/
DECLARE

BEGIN
<execution block>
.
.
EXCEPTION
WHEN <exceptionl_name>
THEN
<Exception handling code for the “exception 1 _name’' >
WHEN OTHERS
THEN
<Default exception handling code for all exceptions >
END;
/

Exception Trapping Functions: SQLCODE and SQLERRM

Oracle uses two built in functions for catching exceptions and getting its information, SQLCODE and
SQLERRM.

SQLCODE returns the error number for the latest occurred exception in the PL/SQL block, while
SQLERRM returns the error message associated with the latter error number.

TYPES OF ERROR
 Compile time error
 Run time error
DIFFERENCE BETWEEN EXCEPTION & ERROR

EXCEPTION ERROR

The query will return Exception on run time. The query will throw the Error on compile time.

We can able to handle and continue to work. We can rectify and get the exact result.

IMPORTANT POINTS TO NOTE IN EXCEPTION

 In function, an exception should always either return value or raise the exception further. else Oracle
will throw 'Function returned without a value' error at run-time.
 Transaction control statements can be given at exception handling block.
 SQLERRM and SQLCODE are the in-built functions that will give the exception message and code.
 If an exception is not handled then by default all the active transaction in that session will be rolled
back.
 RAISE_APPLICATION_ERROR (-<error_code>, <error_message>) can be used instead of RAISE to
raise the error with user code and message. Error code should be greater than 20000 and prefixed with
'-'.

TYPE OF HANDLING EXCEPTION:


 Pre-defined exception
 User defined exception
A user defined exception is an error, which is defined by programmer.
 Non User defined exception
Raise_application error
 Here we can able to create our own error messages, which can be more descriptive than
named exception.
 ORACLE ERROR RANGE from -00000 to -19999
 USER ERROR RANGE from -20000 to -20999

Pragma exception_init
 Here we can give the name for pre-defined exception.
 We can associate named exception with particular oracle error codes.

SQLCODE

 Sqlerrm returns current error message and sqlcode returns current error message code.
 It will support for all exception types.
PRE-DEFINED EXCEPTION
 Oracle has predefined several exceptions like,

EXCEPTION ORACLE ERROR SQL CODE


ZERO_DIVIDE ORA-01476 -1476
NO_DATA_FOUND ORA-01403 100
DUP_VAL_ON_INDEX ORA-00001 -1
TOO_MANY_ROWS ORA-01422 -1422
VALUE_ERROR ORA-06502 -6502
CURSOR_ALREADY_OPEN ORA-06511 -6511

Error Named Exception


ORA-00001 DUP_VAL_ON_INDEX
ORA-01001 INVALID_CURSOR
ORA-01012 NOT_LOGGED_ON
ORA-01017 LOGIN_DENIED
ORA-01403 NO_DATA_FOUND
ORA-01422 TOO_MANY_ROWS
ORA-01476 ZERO_DIVIDE
ORA-01722 INVALID_NUMBER
ORA-06504 ROWTYPE_MISMATCH
ORA-06511 CURSOR_ALREADY_OPEN
ORA-06530 ACCESS_INTO_NULL
ORA-06531 COLLECTION_IS_NULL
ORA-06532 SUBSCRIPT_OUTSIDE_LIMIT
ORA-06533 SUBSCRIPT_BEYOND_COUNT
Exception Error Code Exception Reason
ACCESS_INTO_NULL ORA-06530 Assign a value to the attributes of uninitialized objects
CASE_NOT_FOUND ORA-06592 None of the 'WHEN' clause in CASE statement satisfied and no 'ELSE' clause is specified
COLLECTION_IS_NULL ORA-06531 Using collection methods (except EXISTS) or accessing collection attributes on a uninitialized collections
CURSOR_ALREADY_OPEN ORA-06511 Trying to open a cursor which is already opened
DUP_VAL_ON_INDEX ORA-00001 Storing a duplicate value in a database column that is a constrained by unique index
INVALID_CURSOR ORA-01001 Illegal cursor operations like closing an unopened cursor
INVALID_NUMBER ORA-01722 Conversion of character to a number failed due to invalid number character
NO_DATA_FOUND ORA-01403 When 'SELECT' statement that contains INTO clause fetches no rows.
ROW_MISMATCH ORA-06504 When cursor variable data type is incompatible with the actual cursor return type
SUBSCRIPT_BEYOND_COUNT ORA-06533 Referring collection by an index number that is larger than the collection size
SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 Referring collection by an index number that is outside the legal range (eg: -1)
TOO_MANY_ROWS ORA-01422 When a 'SELECT' statement with INTO clause returns more than one row
VALUE_ERROR ORA-06502 Arithmetic or size constraint error (eg: assigning a value to a variable that is larger than the variable size)
ZERO_DIVIDE ORA-01476 Dividing a number by '0'

DECLARE
--variable
--cursor
Declaring exception
BEGIN
EXCEPTION
--exception handling
END;

Raising Exceptions Implicitly

These exceptions are automatically processed and raised by Oracle server.

As soon as Oracle server encounters any illogical flow in the program flow, it stops further execution of
program, identifies and throws the appropriate exception; program terminates abruptly.

DECLARE
L_DEPTID NUMBER := 10;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');

SELECT EMPLOYEE_NAME,SALARY
INTO L_ENAME, L_SAL
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;

DBMS_OUTPUT.PUT_LINE('After SQL query');


END;
/

BEFORE SQL query


DECLARE
*
ERROR at line 1:
ORA-01422: exact fetch RETURNS more than requested NUMBER OF ROWS
ORA-06512: at line 7

Raising Exception Explicitly: System Defined and User Defined Exceptions

A developer can explicitly raise the system defined exceptions. In the Code [], the TOO_MANY_ROWS
exception can be captured by defining an exception handler in the EXCEPTION section.

DECLARE
L_DEPTID NUMBER := 10;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
SELECT EMPLOYEE_NAME,SALARY
INTO L_ENAME, L_SAL
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE ('Use Oracle Bulk Collect feature or Cursor to select multiple rows from
a table');
END;
/

BEFORE SQL query


USE Oracle Bulk Collect feature OR Cursor TO SELECT multiple ROWS FROM a TABLE

PL/SQL PROCEDURE successfully completed.

PRE DEFINE EXCEPTION


ZERO_DIVIDE
DECLARE
i NUMBER(10);
BEGIN
SELECT 1/0 INTO i
FROM dual;
dbms_output.put_line(i);
EXCEPTION
WHEN zero_divide THEN
dbms_output.put_line('Please enter the valid divisor');
END;
/
Please enter the valid divisor

PL/SQL procedure successfully completed.


NO_DATA_FOUND
SQL> CREATE TABLE t1
2 (
3 salary NUMBER(10)
4 );

Table created.

SQL> SELECT * FROM t1;

no rows selected
DECLARE
i NUMBER(10);
BEGIN
SELECT salary INTO i
FROM t1;
dbms_output.put_line(i);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('There is no data inside the table');
END;
/
There is no data inside the table

PL/SQL procedure successfully completed.

DECLARE
L_DEPTID NUMBER := 15;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
CURSOR C IS
SELECT EMPLOYEE_NAME,SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
OPEN C;
FETCH C INTO L_ENAME, L_SAL;
IF C%ROWCOUNT = 0 THEN
RAISE NO_DATA_FOUND;
END IF;
CLOSE C;
DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/

BEFORE SQL query


No Employees IN the department

PL/SQL PROCEDURE successfully completed.

DECLARE
v_nm Employees.first_name%TYPE;
BEGIN
SELECT
first_name
INTO
v_nm
FROM
employees
WHERE
first_name='sasik';
dbms_output.put_line('The name is :'||v_nm);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('Please enter the valid name');
END;
/
Please enter the valid name

PL/SQL procedure successfully completed.


TOO_MANY_ROWS

DECLARE
L_DEPTID NUMBER := 10;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
SELECT EMPLOYEE_NAME,SALARY
INTO L_ENAME, L_SAL
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE ('Use Oracle Bulk Collect feature or Cursor to select multiple rows from
a table');
END;
/

BEFORE SQL query


USE Oracle Bulk Collect feature OR Cursor TO SELECT multiple ROWS FROM a TABLE

PL/SQL PROCEDURE successfully completed.

DECLARE
v_salary NUMBER(10);
BEGIN
SELECT
salary
INTO
v_salary
FROM
employees
WHERE
salary=17000;
dbms_output.put_line('The salary is :'||v_salary);
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('Please declare explicit cursor');
WHEN no_data_found THEN
dbms_output.put_line('Please enter the valid data');
END;
/
Please declare explicit cursor

PL/SQL procedure successfully completed.


SQL> SELECT first_name,salary
2 FROM employees
3 WHERE salary =17000;

FIRST_NAME SALARY
-------------------- ----------
Neena 17000
Lex 17000

2 rows selected.

DUP_VAL_ON_INDEX
SQL> CREATE TABLE t1
2 (
3 id NUMBER(10),
4 CONSTRAINT t1_id_pk PRIMARY KEY(id)
5 );

Table created.

SQL> INSERT INTO t1 VALUES(7000);

1 row created.

SQL> SELECT * FROM t1;


ID
----------
7000

1 row selected.
DECLARE
i NUMBER(10);
BEGIN
INSERT INTO t1 VALUES(7000);
EXCEPTION
WHEN dup_val_on_index THEN
dbms_output.put_line('Id already exist');
END;
/
Id already exist

PL/SQL procedure successfully completed.


OTHERS
DECLARE
i NUMBER(10);
BEGIN
SELECT 1/0 INTO i
FROM dual;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('The table is empty');
WHEN dup_val_on_index THEN
dbms_output.put_line('Id already exist');
WHEN others THEN
dbms_output.put_line('Some other error');
END;
/
Some other error
PL/SQL procedure successfully completed.
--------------------->>---------------<<----------------------

User Defined Exceptions

User defined exceptions allow the developers to create their own customized exceptions and raise them
within the program wherever required. They are declared in the DECLARE section of the block with type
as EXCEPTION and raised using RAISE statement.

In Oracle, other than the above-predefined exceptions, the programmer can create their own exception and
handle them. They can be created at a subprogram level in the declaration part. These exceptions are
visible only in that subprogram. The exception that is defined in the package specification is public
exception, and it is visible wherever the package is accessible.

SYNTAX

DECLARE
<exception_name> EXCEPTION;
BEGIN
<Execution block>
EXCEPTION
WHEN <exception_name> THEN
<Handler>
END;

DECLARE
i CHAR(1):='M';
GENDER_ERROR EXCEPTION;
BEGIN
IF i NOT IN ('M','F') THEN
raise gender_error;
END IF;
dbms_output.put_line('The gender is :'||i);
EXCEPTION
WHEN gender_error THEN
dbms_output.put_line('Invalid option please enter (M/F)');
END;
/
The gender is :M

PL/SQL procedure successfully completed.

DECLARE
L_DEPTID NUMBER := 15;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
LOCAL_EXCEPTION EXCEPTION;
CURSOR C IS
SELECT EMPLOYEE_NAME,SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
OPEN C;
FETCH C INTO L_ENAME, L_SAL;
IF C%ROWCOUNT =0 THEN
RAISE LOCAL_EXCEPTION;
END IF;
CLOSE C;
DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
WHEN LOCAL_EXCEPTION THEN
DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/

BEFORE SQL query


No Employees IN the department

PL/SQL PROCEDURE successfully completed.

DECLARE
i CHAR(1):='f';
GENDER_ERROR EXCEPTION;
BEGIN
IF i NOT IN ('M','F') THEN
raise gender_error;
END IF;
dbms_output.put_line('The gender is :'||i);
EXCEPTION
WHEN gender_error THEN
dbms_output.put_line('Invalid option please enter (M/F)');
END;
/
Invalid option please enter (M/F)

PL/SQL procedure successfully completed.

--------------------->>---------------<<----------------------

NON USER DEFINED EXCEPTION


 Raise_application error
 Pragma exception_init
RAISE_APPLICATION_ERROR

Customizing the Error Numbers: RAISE_APPLICATION_ERROR

Oracle facilitates the developer by privileging them to create an error number of their own choice and
associating them with a customized message. RAISE_APPLICATION_ERROR is an Oracle API, which
allows choosing the error numbers in range of -20000 to -20999 and fix them with an error message

All the predefined exceptions are raised implicitly whenever the error occurs. But the user-defined
exception needs to be raised explicitly.
This can be achieved using the keyword 'RAISE'. This can be used in any of the ways mentioned below.
If 'RAISE' is used separately in the program, then it will propagate the already raised exception to the
parent block. Only in exception block can be used as shown below.

SYNTAX
RAISE_APPLICATION_ERROR (error_number, error_message[, {TRUE | FALSE}])

DECLARE
<Variable declaration>
BEGIN
<Execution block>
EXCEPTION
WHEN <exception_name> THEN
<Handler>
RAISE;
END;
/

DECLARE
L_DEPTID NUMBER := 15;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
CURSOR C IS
SELECT EMPLOYEE_NAME,SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
OPEN C;
FETCH C INTO L_ENAME, L_SAL;
IF C%ROWCOUNT =0 THEN
RAISE_APPLICATION_ERROR(-20001,' No Employees in the department');
END IF;
CLOSE C;
DBMS_OUTPUT.PUT_LINE('After SQL query');
END;
/

BEFORE SQL query


DECLARE
*
ERROR at line 1:
ORA-20001: No Employees IN the department
ORA-06512: at line 14

DECLARE
BEGIN
<Execution block>
RAISE <exception_name>
EXCEPTION
WHEN <exception_name> THEN
<Handler>
END;

SQL> SELECT 102 FROM empl;


SELECT 102 FROM empl
*
ERROR at line 1:
ORA-00942: table or view does not exist

ORA -00000 to -19999 | oracle error rang


ORA -20000 to -20999 | user error range

DECLARE
i CHAR(1):='O';
BEGIN
IF i NOT IN('M','F')THEN
RAISE_APPLICATION_ERROR(-20001,'Try later');
END IF;
dbms_output.put_line(i);
END;
/
DECLARE
*
ERROR at line 1:
ORA-20001: Try later
ORA-06512: at line 5

SET SERVEROUTPUT ON SIZE 100000;


DECLARE
-- define exceptions
BELOW_SALARY_RANGE EXCEPTION;
ABOVE_SALARY_RANGE EXCEPTION;
-- salary variables
n_salary employees.salary%TYPE;
n_min_salary employees.salary%TYPE;
n_max_salary employees.salary%TYPE;
-- input employee id
n_emp_id employees.employee_id%TYPE := &emp_id;
BEGIN
SELECT salary,
min_salary,
max_salary
INTO n_salary,
n_min_salary,
n_max_salary
FROM employees
INNER JOIN jobs ON jobs.job_id = employees.job_id
WHERE employee_id = n_emp_id;

IF n_salary < n_min_salary THEN


RAISE BELOW_SALARY_RANGE;
ELSIF n_salary > n_max_salary THEN
RAISE ABOVE_SALARY_RANGE;
END IF;

dbms_output.put_line('Employee ' || n_emp_id ||


' has salary $' || n_salary );

EXCEPTION
WHEN BELOW_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary below the salary range');
WHEN ABOVE_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary above the salary range');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ' || n_emp_id || ' not found');
END;
/
--------------------->>---------------<<----------------------
USE PRAGMA EXCEPTION_INIT FOR ERROR HANDLING

Associating a User Defined Exception with an Error Number (or Exception Code)

A user defined exception can be associated with an error number using PRAGMA EXCEPTION_INIT.
The pragma is a compiler directive which hints the compiler to accept the directions provided in the
program. The PRAGMA EXCEPTION_INIT directs the compiler to align the user defined exception with
a self assigned error number. The error number must be one of the valid ORA error codes, which are
defined by the server.

Format: PRAGMA EXCEPTION_INIT ( Exception_Name , SqlCode# )


 Use this to name any unnamed ORA- error that might be raised by your program. If you don't, you
have to catch those errors with 'WHEN OTHERS.'
 For a user-defined exception, assign a code between –20999 and –20000 to SQLCode so it can be
raised.

SYNTAX

PRAGMA EXCEPTION_INIT([EX NAME],[ERROR NUMBER], [TRUE | FALSE])

DECLARE
L_DEPTID NUMBER := 15;
L_ENAME VARCHAR2(100);
L_SAL NUMBER;
LOCAL_EXCEPTION EXCEPTION;
PRAGMA EXCEPTION_INIT(LOCAL_EXCEPTION, -100);
CURSOR C IS
SELECT EMPLOYEE_NAME,SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = L_DEPTID;
BEGIN
DBMS_OUTPUT.PUT_LINE('Before SQL query');
OPEN C;
FETCH C INTO L_ENAME, L_SAL;
IF C%ROWCOUNT =0 THEN
RAISE LOCAL_EXCEPTION;
END IF;
CLOSE C;
DBMS_OUTPUT.PUT_LINE('After SQL query');
EXCEPTION
WHEN LOCAL_EXCEPTION THEN
DBMS_OUTPUT.PUT_LINE (‘Exception Error NUMBER:’||SQLCODE);
DBMS_OUTPUT.PUT_LINE ('No Employees in the department');
END;
/

BEFORE SQL query


Exception Error NUMBER:-100
No Employees IN the department

PL/SQL PROCEDURE successfully completed.

SQL> Drop table test_exinit;

Table dropped.

SQL> CREATE TABLE test_exinit


2 (
3 id NUMBER(2) NOT NULL
4 );

Table created.

SQL>
SQL> INSERT INTO test_exinit VALUES(1);

1 row created.

SQL> SELECT * FROM test_exinit;

ID
----------
1

1 row selected.
SQL> INSERT INTO test_exinit VALUES(null);
INSERT INTO test_exinit VALUES(null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("HR"."TEST_EXINIT"."ID")
DECLARE
not_null EXCEPTION;
PRAGMA EXCEPTION_INIT (not_null,-01400);
BEGIN
INSERT INTO test_exinit VALUES(null);
EXCEPTION
WHEN not_null THEN
dbms_output.put_line('Null values is not allowed');
END;
/
Null values is not allowed

PL/SQL procedure successfully completed.


--------------------->>---------------<<----------------------
ERROR LOG BY USING EXCEPTION
DROP TABLE errors;
CREATE TABLE Errors
(
Code NUMBER
,Message VARCHAR2(64)
,Happened TIMESTAMP
);
DECLARE

vSqlCode NUMBER;
vSqlErrM VARCHAR2(64);
v_first_name VARCHAR2(30);
BEGIN
SELECT
First_name
INTO
v_first_name
FROM
Employees
WHERE
employee_id = 11;
EXCEPTION
WHEN OTHERS THEN
vSqlCode := SqlCode;
vSqlErrM := Substr(SqlErrM, 1 ,64);
Dbms_Output.Put_Line('Code '||vSqlCode
|| ': ' ||vSqlErrM);
INSERT INTO Errors Values
(
vSqlCode
,vSqlErrM
,SYSTIMESTAMP
);
END;
Code 100: ORA-01403: no data found

PL/SQL procedure successfully completed.


DROP TABLE t1;
DROP TABLE test_exinit;
DROP TABLE errors;

Understand PL/SQL's exception handling architecture.


DECLARE
aname VARCHAR2 (5);
BEGIN
BEGIN
aname := 'Big String';
DBMS_OUTPUT.put_line (aname);
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.put_line ('Inner block');
END;

DBMS_OUTPUT.put_line (SQLCODE);

DBMS_OUTPUT.put_line ('What error?');


EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.put_line ('Outer block');
END;
/
Inner block
0
What error?

DECLARE
aname VARCHAR2(5);
BEGIN
DECLARE
aname VARCHAR2(5) := 'Big String';
BEGIN
DBMS_OUTPUT.PUT_LINE (aname);

EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE ('Inner block');
END;

DBMS_OUTPUT.put_line (SQLCODE);
DBMS_OUTPUT.PUT_LINE ('What error?');
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE ('Outer block');
END;
/
Outer block

CREATE TABLE employees AS SELECT * FROM hr.employees

DECLARE
aname VARCHAR2(5);
BEGIN
DECLARE
aname VARCHAR2(5) := 'Justice';
loc INTEGER := 1;
BEGIN
loc := 2;
DBMS_OUTPUT.PUT_LINE (aname);

loc := 3;
DELETE FROM employees;

EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE ('Got as far as ' || loc);
ROLLBACK;
END;
DBMS_OUTPUT.PUT_LINE ('What error?');
ROLLBACK;
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE ('Outer block');
ROLLBACK;
END;
/
Outer block
BEGIN
<<outer>>
DECLARE
aname VARCHAR2 (5);
BEGIN
<<inner>>
DECLARE
aname VARCHAR2 (20);
BEGIN
OUTER.aname := 'Big String';
EXCEPTION
WHEN VALUE_ERROR
THEN
RAISE NO_DATA_FOUND;

WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line ('Inner block');
END INNER;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line ('Outer block');
END OUTER;
END;
/
Outer block
DECLARE
v_totsal NUMBER;
v_ename employees.last_name%TYPE;
BEGIN
/* There are no rows with department_id = -15 */
SELECT SUM (salary) INTO v_totsal
FROM employees
WHERE department_id = -15;

DBMS_OUTPUT.PUT_LINE ('Total salary: ' || v_totsal);

SELECT last_name INTO v_ename


FROM employees
WHERE salary =
(SELECT MAX (salary)
FROM employees WHERE department_id = -15);
DBMS_OUTPUT.PUT_LINE (
'The winner is: ' || v_ename);
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.PUT_LINE ('Outer block');
END;
/
Total salary:
Outer block

DECLARE
PLS_INTEGER VARCHAR2 (1);
NO_DATA_FOUND EXCEPTION;
BEGIN
SELECT dummy
INTO PLS_INTEGER
FROM DUAL
WHERE 1 = 2;

IF PLS_INTEGER IS NULL
THEN
RAISE NO_DATA_FOUND;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line ('No dummy!');
END;
/
ORA-01403: no data found
--------------------->>---------------<<----------------------

You might also like