Chapter Eighteen Exception Handling

53
Chapter 18: Exception Ha ndling 1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception messages & customization – Blocks & exception propagation

description

Chapter Eighteen Exception Handling. Objective: Define exceptions List types of exception handlers Trap errors Exception messages & customization Blocks & exception propagation. Introduction. DECLARE PE_ratioNUMBER(3,1); BEGIN SELECT Price/earning INTO PE_ratio FROM Stock - PowerPoint PPT Presentation

Transcript of Chapter Eighteen Exception Handling

Page 1: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 1

Chapter EighteenException Handling

Objective:– Define exceptions

– List types of exception handlers

– Trap errors

– Exception messages & customization

– Blocks & exception propagation

Page 2: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 2

Introduction

DECLAREPE_ratio NUMBER(3,1);

BEGINSELECT Price/earningINTO PE_ratioFROM StockWHERE Symbol = ‘BBY’;INSERT INTO table1(Symbol, ratio)VALUES (‘BBY’, PE_ratio);COMMIT;

EXCEPTIONWHEN ZERO_DIVIDE THEN

INSERT INTO table1(Symbol, ratio)VALUES (‘BBY’, NULL);COMMIT;

WHEN OTHERS THENROLLBACK;

END;

Page 3: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 3

Adapting an Exception Handling Strategy

• How to log an error?• How to report an error to users?• When to log an error?• When to report an error to users?• Who should receive the error log & how to make

correction?• How to handle the transaction after an error occurred?• Where should I declare my error handling:

– For each block– Only for top level

Page 4: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 4

Definition Of Exception Handling:

• “Methods of a program that react and deal with runtime errors”.

• ORA-1000 Unique constraint violated

• ORA-06502 PL/SQL: numeric or value error

• ORA-01403 No data is retrieved from SELECT statement (NO_DATA_FOUND)

Page 5: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 5

Exception Handling

• Facts:– Exception is an identifier in PL/SQL

– Exception mechanism of PL/SQL is the same as ADA

– It is similar to JAVA: but unlike JAVA, exception is not an object

– Exceptions are designed for run-time error handling -not compile time.

– Unlike C, Oracle system has error handling methods

Page 6: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 6

Exception Handling

How do we handle exceptions:

• Trap the exception

• Propagate it to the calling environment

Page 7: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 7

Handling Exceptions

Trap the Exception

DECLARE

…..

BEGIN

….

EXCEPTION

…..

END

Propagate the ExceptionDECLARE

…..

BEGIN

….

EXCEPTION

END

Exception propagates to calling environment

Page 8: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 8

Exception Handling

Trap the exception:DECLARE….BEGIN…. <Exception is raised>EXCEPTION…. <Exception is trapped>END

If exception is not handled successfully, block terminates with failure and the exception propagates to the calling block

Page 9: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 9

Exception Types

1. Predefined Oracle Server

2. Non-predefined Oracle Server

3. User-defined

Page 10: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 10

Exception Types:

1. Predefined Oracle Server errors:– No declaration is needed– Oracle Server raises them implicitly

ORA-01403 NO_DATA_FOUNDORA-01422 TOO_MANY_ROWSORA-01476 ZERO_DIVIDEORA-06500 STORAGE_ERRORORA-06530 ACCESS_INTO_NULLORA-06592 CASE_NOT_FOUNDORA-00001 DUP_VAL_ON_INDEX

Page 11: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 11

Exception Types:

2. Non_Predefined Oracle Server errors– Other Standard Oracle Server errors– Declared within the declarative section– Oracle Server raises them implicitly

Page 12: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 12

Exception Types:

3. User_defined– User determines an abnormal condition– Declared in declaration section– It is raised explicitly

DECLAREe_TooManyNumbers EXCEPTION;

Page 13: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 13

Raising Exceptions:

• When an error occurs, an exception is raised

• User_defined exceptions are raised explicitly via RAISE command

• Other exceptions are raised by EXCEPTION_INIT pragma

Page 14: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 14

Raising USER_DEFINED Exceptions

• Example

DECLAREe_TooManyNumbers EXCEPTION;V_NoStudent NUMBER(4);V_MaxStudent NUMBER(4);

BEGINSELECT Current_Students, Max_StudentsINTO V_NoStudent, V_MaxStudentFROM classesWHERE C_Num=641 AND Dept=‘COSC’;IF V_NoStudent > V_MaxStudent THEN

RAISE e_TooManyNumbers;END IF;

END;

Page 15: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 15

Ways an Exception may be Raised

• Oracle raises an exception when it detects an error

• User may raise an exception with RAISE

• User may raise an exception with RAISE_APPLICATION_ERROR built in procedure

Page 16: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 16

Type of RAISE Statement

• RAISE exception_name;

• RAISE Package_name.exception;

• RAISE;

Page 17: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 17

Example

DECLAREinvalid_id EXCEPTION;id_value VARCHAR2;

BEGINid_value := id_for(‘Mike’);IF id_value BETWEEN 1111 AND 2222 THEN

….ELSE

RAISE invalid_id;END IF;

END;

• RAISE ZERO_DIVIDE; -- Predefined Oracle exception

Page 18: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 18

Re-raise Exceptions

BEGINBEGIN

IF X=-10 THENRAISE X_IS_LOW;

END IF;EXCEPTION

WHEN X_IS_LOW THEN DBMS_OUTPUT.PUT_LINE (X || ’is low’);

RAISE;END…

EXCEPTIONWHEN X_IS_LOW THEN

--Handle Error HereEND;

Page 19: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 19

Example

• RAISE;• Use this form if you want to re-raise the same exception

from within an exception handler

EXCEPTIONWHEN My_error THEN

DBMS_OUTPUT.PUT_LINE(‘Error description’);

--pass on the exception to the enclosing blockRAISE;

END;

Page 20: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 20

RAISE_APPLICATION_ERROR(Customize The Error Messages)

SyntaxRAISE_APPLICATION_ERROR(err_No, Message)[, TRUE | FALSE];

• It lets you issue a non standard user defined error message from stored subprograms• Called only from an executing stored subprogram

…..BEGIN

SELECT count(*)INTO xFROM USERTABLE;IF x<100 THEN

RAISE_APPLICATION_ERROR(-20202, ‘Expect at least 100 rows’);ELSE

….END;

Page 21: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 21

Example

BEGINDELETE FROM deptWHERE deptNo = V_deptNo;IF SQL%NOTFOUND THEN -- in execution part

RAISE_APPLICATION_ERROR(-20002, ‘Error in deleting depart no.’);END IF;……

Page 22: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 22

Raising Predefined Exceptions

• Example

BEGIN

INSERT INTO Students (id, name)

VALUES (111, ‘Mark’);

INSERT INTO Students (id, name)

VALUES (111, ‘Mary’);

DUP_VAL_ON_INDEX

Page 23: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 23

1-Trapping Exceptions

Syntax

EXCEPTIONWHEN exception1 THEN

statement1;statement2;…

[WHEN exception2 THENstatement1;statement2;

…][WHEN OTHERS THEN

statement1;statement2;….]

Page 24: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 24

Trapping Exceptions Guidelines

• EXCEPTION Keyword starts exception handling section

• Several exception handlers are allowed• Only one handler is processed before leaving

the block• WHEN OTHERS is the Last clause:• Exceptions can not appear in assignment

statement or SQL statement

Page 25: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 25

Several Places can Raise the Same Exception:

DECLAREe_TooManyNumbers EXCEPTION;V_NoStudent NUMBER(4);V_MaxStudent NUMBER(4);

BEGINSELECT Current_Students, Max_StudentsINTO V_NoStudent, V_MaxStudentFROM classesWHERE C_Num=641 AND Dept=‘COSC’;IF V_Student > V_MaxStudent THEN

RAISE e_TooManyNumbers;END IF;

Continued

Page 26: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 26

Example

EXCEPTIONWHEN e_TooManyNumbers THEN

INSERT INTO log_file (info)

VALUES (‘COSC 641 has:‘ || V_NoStudent || ‘Max No is:’ || V_MaxStudent);

END;

Page 27: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 27

Two or More Exceptions Executing the Same Sequence of StatementsIF …

RAISE a;IF …

RAISE b;…

EXCEPTIONWHEN a or b or c THEN

Page 28: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 28

Example

EXCEPTION

WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN

INSERT INTO log_file (info)

VALUES (‘ ‘);

WHEN OTHERS THEN

INSERT INTO log_file (info)

VALUES (‘ ‘);

END;

Page 29: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 29

2 - Trapping Non_Predefined Oracle Server Errors

1. Declare the exception first

2. Code the PRAGMA EXCEPTION_INIT

3. Handle the raised exception

Page 30: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 30

Non-Predefined Error Syntax

exceptionName EXCEPTION;

PRAGMA EXCEPTION_INIT(exceptionName, error_No);

Page 31: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 31

Example

DECLAREe_Faculty_Remaining EXCEPTION;PRAGMA EXCEPTION_INIT (e_Faculty_Remaining, -6501);V_deptNo dept.deptNo%TYPE := &p_deptno;

BEGINDELETE FROM deptWHERE deptNo = V_deptNo;COMMIT;

EXCEPTIONWHEN e_faculty_Remaining THEN

DBMS_OUTPUT.PUT_LINE(‘can not remove dept, there are faculty in the dept’);

END;

Page 32: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 32

3 - Trapping User_defined Exceptions

1. Declare the exception

2. Explicitly raise the exception by using RAISE statement

3. Handle the raised exception

Page 33: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 33

User defined Error Syntax

exceptionName EXCEPTION:

RAISE exceptionName;

Page 34: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 34

Example

DECLAREe_Invalid_product EXCEPTION;

BEGINUPDATE ProductSET desc= ‘&Product_desc’WHERE ProductId = &Product_No;IF SQL%NOTFOUND THEN

RAISE e_Invalid_Product;END IF;COMMIT;

EXCEPTIONWHEN e_Invalid_Product THEN

DBMS_OUTPUT.PUT_LINE(‘Invalid Product Numbers’);END;

Page 35: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 35

Calling Environments

SQL*PLUS: Displays error number & message to screen

Precompiler Application:

Access error Number via the SQLCA data structure

PL/SQL block:

Traps exception in exception handling block

Page 36: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 36

Example of Propagating Exceptions:DECLARE

a EXCEPTION;b EXCEPTION;PARAGMA EXCEPTION_INIT(b, -2292);

BEGINFOR counter IN fac_cursor LOOPBEGIN

SELECT …UPDATE …IF SQL%NOTFOUND THEN

RAISE a;END IF;

EXCEPTIONWHEN b THEN ….WHEN a THEN ….

END;END LOOP;

EXCEPTIONWHEN NO_DATA_FOUND THEN ….WHEN TOO_MANY_ROWS THEN ….

END;

Page 37: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 37

Exception Propagation:BEGIN

BEGINIF NUM=-1 THEN

RAISE A;ELSIF NUM=1 THEN

RAISE B;ELSE

RAISE C;EXCEPTION

WHEN A THEN…

END;…EXCEPTION

WHEN B THEN…

END;

Page 38: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 38

Declarations Exception:

DECLAREMax CONSTANT NUMBER(2):=999;--

exception

BEGINNULL;

EXCEPTIONWHEN OTHERS THEN

…END;/

Page 39: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 39

Handlers Exception in Exception Clause:

....

EXCEPTIONWHEN INVALID_NUMBER THEN

INSERT INTO …--RAISE DUP_VAL_ON_INDEXWHEN DUP_VAL_ON_INDEX THEN

….END;

Page 40: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 40

PRACTICE:

• Write a procedure to insert name and salary of faculty members whose salary is plus or minus $x (x is passed as a parameter) of the salary, into faculty_stat table with the following exceptions:

• If there is no faculty salary in that range, write a message into logfile table ‘No faculty in $x range’

• If there is more that one faculty, write the sum of faculty members in that range.

• Any other exception should go to the logfile with the appropriate message.

Page 41: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 41

Functions for Trapping Exceptions

SQLCODEReturns the numeric value for the last error

raised

SQLERRMReturns the message associated with the error

number

Page 42: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 42

Example

DECLAREa NUMBER;b VARCHAR2(256);

BEGIN…..

EXCEPTION.….WHEN OTHERS THEN

ROLLBACK;a:= SQLCODE;b:= SQLERRM;INSERT INTO errors VALUES (a, b);

END;

Page 43: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 43

Example

CREATE OR REPLACE PACKAGE dynamicSQLIs

invalid_Table_Name EXCEPTION;PRAGMA EXCEPTION_INIT(invalid_Table_Name, -903);

invalid_Col_Name EXCEPTION;PRAGMA EXCEPTION_INIT(invalid_Col_Name, -904);

.

.

.END dynamicSQL;

To Trap:WHEN dynamicSQL.invalid_Col_Name THEN

……

Page 44: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 44

Example

CREATE OR REPLACE PACKAGE ErrorNo ISError_One CONSTANT NUMBER:=-20050;Exc_One EXCEPTION;PRAGMA EXCEPTION_INIT(Exc_One, Error_One);

Error_Two CONSTANT NUMBER:=-20051;Exc_TwoEXCEPTION;PRAGMA EXCEPTION_INIT(Exc_Two, Error_Two);

END ErrorNo;

PROCEDURE …is ….BEGIN

IF …THEN RAISE_APPLICATION_ERROR(ErrorNo.Error_One, ‘Description of Error’);END IF;

Page 45: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 45

Calling a Procedure or Block to Check for Errors

1. SQL>SET SERVEROUTPUT ON SIZE 1000000 FORMAT TRUNCATED

2. SQL>EXEC deposit(1111, 250, ‘check’ );

Page 46: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 46

Finding the Location of Errors

BEGIN

SELECT …..

SELECT…..

SELECT….

EXCEPTION

……..

END;

Page 47: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 47

Method 1: Finding the location of Errors

BEGINSELECT …..v_counter:=1;SELECT…..v_counter:=2;SELECT….v_counter:=3;

EXCEPTIONWHEN NO_DATA_FOUND THEN

INSERT INTO errorsVALUES (‘Error in statement ‘ || v_counter);

END;

Page 48: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 48

Method 2: Put Each Exception in a Block

BEGINSELECT …..EXCEPTION…

END;BEGIN

SELECT…..EXCEPTION

END;……

Page 49: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 49

CALL STACK

V_callstack VARCHAR2(2000);

BEGIN V_callstack := DBMS_UTILITY.FORMAT_CALL_STACK;

Page 50: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 50

Capture Rows that Cause Errors:

• Create a table called EXCEPTIONS in your schema

• Script is called ‘utlexcpt.sql’ and is in /rdbms/admin directory

• Exceptions table contains four columns:

Row_ID, Owner, Table_Name, Constraint.

Page 51: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 51

Capture Rows that Cause Errors:

Example:--Enable a primary key

ALTER TABLE faculty ENABLE PRIMARY KEYexceptions into exceptions;--If enable failSELECT Owner, Table_Name, constraint FROM exceptions;--What row cause thisSELECT * FROM faculty EHERE Row_ID IN (SELECT Row_ID FROM

EXCEPTIONS);

Page 52: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 52

Retrying a Transaction

BEGINFOR I IN 1…100 LOOPBEGIN

SAVEPOINT a;…DELETE FROM faculty

WHERE age = 65;…INSERT INTO Re_facultyVALUES (name, …);--RAISE DUP_VAL_ON_INDEXCOMMIT;

END;EXCEPTION

WHEN DUP_VAL_ON_INDEX THENROLLBACK TO a;

END;

Page 53: Chapter Eighteen Exception Handling

Chapter 18: Exception Handling 53

Predefined Exceptions

Exception Oracle Error SQLCODE Value

CURSOR_ALREADY_OPEN ORA-06511 -6511

INVALID_CURSOR ORA-01001 -1001

NO_DATA_FOUND ORA-01403 +100

SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532

SYS_INVALID_ROWID ORA-01410 -1410

TIMEOUT_ON_RESOURCE ORA-00051 -51

TOO_MANY_ROWS ORA-01422 -1422

ZERO_DIVIDE ORA-01476 -1476