Download presentation
Presentation is loading. Please wait.
Published byDoris Watts Modified over 9 years ago
1
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception messages & customization – Blocks & exception propagation
2
Chapter 18: Exception Handling2 Introduction DECLARE PE_ratioNUMBER(3,1); BEGIN SELECT Price/earning INTO PE_ratio FROM Stock WHERE Symbol = ‘BBY’; INSERT INTO table1(Symbol, ratio) VALUES (‘BBY’, PE_ratio); COMMIT; EXCEPTION WHEN ZERO_DIVIDE THEN INSERT INTO table1(Symbol, ratio) VALUES (‘BBY’, NULL); COMMIT; WHEN OTHERS THEN ROLLBACK; END;
3
Chapter 18: Exception Handling3 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
4
Chapter 18: Exception Handling4 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)
5
Chapter 18: Exception Handling5 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
6
Chapter 18: Exception Handling6 Exception Handling How do we handle exceptions: Trap the exception Propagate it to the calling environment
7
Chapter 18: Exception Handling7 Handling Exceptions Trap the Exception DECLARE ….. BEGIN …. EXCEPTION ….. END Propagate the Exception DECLARE ….. BEGIN …. EXCEPTION … END Exception propagates to calling environment
8
Chapter 18: Exception Handling8 Exception Handling Trap the exception: DECLARE …. BEGIN …. EXCEPTION …. END If exception is not handled successfully, block terminates with failure and the exception propagates to the calling block
9
Chapter 18: Exception Handling9 Exception Types 1.Predefined Oracle Server 2.Non-predefined Oracle Server 3.User-defined
10
Chapter 18: Exception Handling10 Exception Types: 1.Predefined Oracle Server errors: –No declaration is needed –Oracle Server raises them implicitly ORA-01403 NO_DATA_FOUND ORA-01422 TOO_MANY_ROWS ORA-01476 ZERO_DIVIDE ORA-06500 STORAGE_ERROR ORA-06530 ACCESS_INTO_NULL ORA-06592 CASE_NOT_FOUND ORA-00001 DUP_VAL_ON_INDEX
11
Chapter 18: Exception Handling11 Exception Types: 2.Non_Predefined Oracle Server errors –Other Standard Oracle Server errors –Declared within the declarative section –Oracle Server raises them implicitly
12
Chapter 18: Exception Handling12 Exception Types: 3.User_defined –User determines an abnormal condition –Declared in declaration section –It is raised explicitly DECLARE e_TooManyNumbers EXCEPTION;
13
Chapter 18: Exception Handling13 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
14
Chapter 18: Exception Handling14 Raising USER_DEFINED Exceptions Example DECLARE e_TooManyNumbers EXCEPTION; V_NoStudentNUMBER(4); V_MaxStudentNUMBER(4); BEGIN SELECT Current_Students, Max_Students INTO V_NoStudent, V_MaxStudent FROM classes WHERE C_Num=641 AND Dept=‘COSC’; IF V_NoStudent > V_MaxStudent THEN RAISE e_TooManyNumbers; END IF; END;
15
Chapter 18: Exception Handling15 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
16
Chapter 18: Exception Handling16 Type of RAISE Statement RAISEexception_name; RAISEPackage_name.exception; RAISE;
17
Chapter 18: Exception Handling17 Example DECLARE invalid_idEXCEPTION; id_valueVARCHAR2; BEGIN id_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
18
Chapter 18: Exception Handling18 Re-raise Exceptions BEGIN IF X=-10 THEN RAISE X_IS_LOW; END IF; EXCEPTION WHEN X_IS_LOW THEN DBMS_OUTPUT.PUT_LINE (X || ’is low’); RAISE; END … EXCEPTION WHEN X_IS_LOW THEN --Handle Error Here END;
19
Chapter 18: Exception Handling19 Example RAISE; Use this form if you want to re-raise the same exception from within an exception handler EXCEPTION WHEN My_error THEN DBMS_OUTPUT.PUT_LINE(‘Error description’); --pass on the exception to the enclosing block RAISE; END;
20
Chapter 18: Exception Handling20 RAISE_APPLICATION_ERROR (Customize The Error Messages) Syntax RAISE_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 SELECTcount(*) INTO x FROMUSERTABLE; IF x<100 THEN RAISE_APPLICATION_ERROR(-20202, ‘Expect at least 100 rows’); ELSE …. END;
21
Chapter 18: Exception Handling21 Example BEGIN DELETE FROM dept WHERE deptNo = V_deptNo; IF SQL%NOTFOUND THEN -- in execution part RAISE_APPLICATION_ERROR(-20002, ‘Error in deleting depart no.’); END IF; ……
22
Chapter 18: Exception Handling22 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
23
Chapter 18: Exception Handling23 1-Trapping Exceptions Syntax EXCEPTION WHEN exception1 THEN statement1; statement2; … [WHEN exception2 THEN statement1; statement2; …] [WHEN OTHERS THEN statement1; statement2; ….]
24
Chapter 18: Exception Handling24 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
25
Chapter 18: Exception Handling25 Several Places can Raise the Same Exception: DECLARE e_TooManyNumbers EXCEPTION; V_NoStudentNUMBER(4); V_MaxStudentNUMBER(4); BEGIN SELECT Current_Students, Max_Students INTO V_NoStudent, V_MaxStudent FROM classes WHERE C_Num=641 AND Dept=‘COSC’; IF V_Student > V_MaxStudent THEN RAISE e_TooManyNumbers; END IF; Continued
26
Chapter 18: Exception Handling26 Example EXCEPTION WHEN e_TooManyNumbers THEN INSERT INTO log_file (info) VALUES (‘COSC 641 has:‘ || V_NoStudent || ‘Max No is:’ || V_MaxStudent); END ;
27
Chapter 18: Exception Handling27 Two or More Exceptions Executing the Same Sequence of Statements IF … RAISE a; IF … RAISE b; … EXCEPTION WHEN a or b or c THEN …
28
Chapter 18: Exception Handling28 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;
29
Chapter 18: Exception Handling29 2 - Trapping Non_Predefined Oracle Server Errors 1.Declare the exception first 2.Code the PRAGMA EXCEPTION_INIT 3.Handle the raised exception
30
Chapter 18: Exception Handling30 Non-Predefined Error Syntax exceptionNameEXCEPTION; … PRAGMA EXCEPTION_INIT(exceptionName, error_No);
31
Chapter 18: Exception Handling31 Example DECLARE e_Faculty_Remaining EXCEPTION; PRAGMA EXCEPTION_INIT (e_Faculty_Remaining, -6501); V_deptNo dept.deptNo%TYPE := &p_deptno; BEGIN DELETE FROM dept WHERE deptNo = V_deptNo; COMMIT; EXCEPTION WHEN e_faculty_Remaining THEN DBMS_OUTPUT.PUT_LINE(‘can not remove dept, there are faculty in the dept’); END;
32
Chapter 18: Exception Handling32 3 - Trapping User_defined Exceptions 1.Declare the exception 2.Explicitly raise the exception by using RAISE statement 3.Handle the raised exception
33
Chapter 18: Exception Handling33 User defined Error Syntax exceptionNameEXCEPTION: … RAISE exceptionName;
34
Chapter 18: Exception Handling34 Example DECLARE e_Invalid_product EXCEPTION; BEGIN UPDATE Product SET desc= ‘&Product_desc’ WHERE ProductId = &Product_No; IF SQL%NOTFOUND THEN RAISE e_Invalid_Product; END IF; COMMIT; EXCEPTION WHEN e_Invalid_Product THEN DBMS_OUTPUT.PUT_LINE(‘Invalid Product Numbers’); END;
35
Chapter 18: Exception Handling35 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
36
Chapter 18: Exception Handling36 Example of Propagating Exceptions: DECLARE aEXCEPTION; bEXCEPTION; PARAGMA EXCEPTION_INIT(b, -2292); BEGIN FOR counter IN fac_cursor LOOP BEGIN SELECT … UPDATE … IF SQL%NOTFOUND THEN RAISE a; END IF; EXCEPTION WHEN b THEN …. WHEN a THEN …. END; END LOOP; EXCEPTION WHEN NO_DATA_FOUND THEN …. WHEN TOO_MANY_ROWS THEN …. END;
37
Chapter 18: Exception Handling37 Exception Propagation: BEGIN IF NUM=-1 THEN RAISE A; ELSIF NUM=1 THEN RAISE B; ELSE RAISE C; EXCEPTION WHEN A THEN … END; … EXCEPTION WHEN B THEN … END;
38
Chapter 18: Exception Handling38 Declarations Exception: DECLARE MaxCONSTANT NUMBER(2):=999;--exception BEGIN NULL; EXCEPTION WHEN OTHERS THEN … END; /
39
Chapter 18: Exception Handling39 Handlers Exception in Exception Clause:. EXCEPTION WHEN INVALID_NUMBER THEN INSERT INTO … --RAISE DUP_VAL_ON_INDEX WHEN DUP_VAL_ON_INDEX THEN …. END;
40
Chapter 18: Exception Handling40 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.
41
Chapter 18: Exception Handling41 Functions for Trapping Exceptions SQLCODE Returns the numeric value for the last error raised SQLERRM Returns the message associated with the error number
42
Chapter 18: Exception Handling42 Example DECLARE a NUMBER; bVARCHAR2(256); BEGIN ….. EXCEPTION.…. WHEN OTHERS THEN ROLLBACK; a:= SQLCODE; b:= SQLERRM; INSERT INTO errors VALUES (a, b); END;
43
Chapter 18: Exception Handling43 Example CREATE OR REPLACE PACKAGE dynamicSQL Is 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: WHENdynamicSQL.invalid_Col_Name THEN ……
44
Chapter 18: Exception Handling44 Example CREATE OR REPLACE PACKAGE ErrorNo IS Error_OneCONSTANT NUMBER:=-20050; Exc_OneEXCEPTION; PRAGMAEXCEPTION_INIT(Exc_One, Error_One); Error_TwoCONSTANT NUMBER:=-20051; Exc_TwoEXCEPTION; PRAGMAEXCEPTION_INIT(Exc_Two, Error_Two); END ErrorNo; PROCEDURE … is …. BEGIN IF … THEN RAISE_APPLICATION_ERROR(ErrorNo.Error_One, ‘Description of Error’); END IF;
45
Chapter 18: Exception Handling45 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’ );
46
Chapter 18: Exception Handling46 Finding the Location of Errors BEGIN SELECT ….. SELECT…. EXCEPTION …….. END;
47
Chapter 18: Exception Handling47 Method 1: Finding the location of Errors BEGIN SELECT ….. v_counter:=1; SELECT….. v_counter:=2; SELECT…. v_counter:=3; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO errors VALUES (‘Error in statement ‘ || v_counter); END;
48
Chapter 18: Exception Handling48 Method 2: Put Each Exception in a Block BEGIN SELECT ….. EXCEPTION… END; BEGIN SELECT….. EXCEPTION END;……
49
Chapter 18: Exception Handling49 CALL STACK V_callstack VARCHAR2(2000); BEGIN V_callstack := DBMS_UTILITY.FORMAT_CALL_STACK;
50
Chapter 18: Exception Handling50 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.
51
Chapter 18: Exception Handling51 Capture Rows that Cause Errors: Example: --Enable a primary key ALTER TABLE faculty ENABLE PRIMARY KEY exceptions into exceptions; --If enable fail SELECT Owner, Table_Name, constraint FROM exceptions; --What row cause this SELECT * FROM faculty EHERE Row_ID IN (SELECT Row_ID FROM EXCEPTIONS);
52
Chapter 18: Exception Handling52 Retrying a Transaction BEGIN FOR I IN 1…100 LOOP BEGIN SAVEPOINT a; … DELETE FROMfaculty WHERE age = 65; … INSERT INTO Re_faculty VALUES (name, …); --RAISE DUP_VAL_ON_INDEX COMMIT; END; EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK TO a; END;
53
Chapter 18: Exception Handling53 Predefined Exceptions ExceptionOracle ErrorSQLCODE Value CURSOR_ALREADY_OPENORA-06511-6511 INVALID_CURSORORA-01001-1001 NO_DATA_FOUNDORA-01403+100 SUBSCRIPT_OUTSIDE_LIMITORA-06532-6532 SYS_INVALID_ROWIDORA-01410-1410 TIMEOUT_ON_RESOURCEORA-00051-51 TOO_MANY_ROWSORA-01422-1422 ZERO_DIVIDEORA-01476-1476
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.