Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

Procedure and Functions. Procedures Syntax: [CREATE [OR REPLACE]] PROCEDURE Pname [(p1, p2…)][IS | AS] [declarations] BEGIN [Execution Statements] [EXCEPTIONS.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Chapter 4B: More Advanced PL/SQL Programming
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
PL/SQL Agenda: Basic PL/SQL block structure
Exception types In Oracle PL/SQL. Types of exceptions Named system exceptions –Raised as a result of an error in PL/SQL or RDBMS processing. Named programmer-defined.
Exception Handling in PL/SQL. POINTS TO DISCUSS What is Exception Handling Structure of Exception Handling Section Types of Exceptions.
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
1 Agenda Summary of last class Loops Simple Loops WHILE Loops FOR Loops Records Cursors.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
PL/SQL block has the following structure: DECLARE Declaration statements BEGIN Executable statements EXCEPTION Exception-handling statements END ;
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Cursor and Exception Handling By Nidhi Bhatnagar.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
Exceptions Oracle Database PL/SQL 10g Programming Chapter 7.
EE Copyright س Oracle Corporation, All rights reserved. ® Review of PL/SQL.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
L/O/G/O Working with Composite Data Types. Objectives After completing this lesson, you should be able to do the following: –Create user-defined PL/SQL.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
CSIT 313 DB PROGRAMMING EXCEPTION HANDLING. In PL/SQL, an error condition is called an exception. An exception can be either –internally defined (by the.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Distributed Database Applications COSC 5050 Week Five.
Handling Exceptions. 2 home back first prev next last What Will I Learn? Describe several advantages of including exception handling code in PL/SQL Describe.
Oracle 8i Exception Handling. General Syntax DECLARE --- BEGIN --- EXCEPTION WHEN exception_name1 THEN -Error handling statements WHEN exception_name2.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
1 Handling Exceptions Part F. 2 Handling Exceptions with PL/SQL What is an exception? Identifier in PL/SQL that is raised during execution What is an.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
1 ITBIS373 Database Development Lecture 2 – Chapter 4B Introduction to PL/SQL.
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Copyright  Oracle Corporation, All rights reserved. 23 Handling Exceptions.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Oracle 数据库应用 -- PL/SQL 进阶 (3) & Oracle DBA 2016/5/ /5/10.
DB Programming Course Lecture 4. Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is a special section.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ITEC 224 Database Programming
CHAPTER 5 EXCEPTION HANDLING
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Interacting with the Oracle8 Server
Creating Stored Procedures and Functions
Difference between Oracle PL/SQL and MySQL
Interacting with the Oracle Server
Handling Exceptions.
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Handling Exceptions.
SQL PL/SQL Presented by: Dr. Samir Tartir
Database Management Systems 2
Agenda Summary of last class Cursors Loops Records Simple Loops
Interacting with the Oracle Server
Handling Exceptions.
Handling Exceptions.
Database Management Systems 2
Handling Exceptions.
PRACTICE OVERVIEW PL/SQL Part - 1.
Database Programming Using Oracle 11g
Presentation transcript:

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

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;

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

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 PL/SQL: numeric or value error ORA No data is retrieved from SELECT statement (NO_DATA_FOUND)

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

Chapter 18: Exception Handling6 Exception Handling How do we handle exceptions: Trap the exception Propagate it to the calling environment

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

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

Chapter 18: Exception Handling9 Exception Types 1.Predefined Oracle Server 2.Non-predefined Oracle Server 3.User-defined

Chapter 18: Exception Handling10 Exception Types: 1.Predefined Oracle Server errors: –No declaration is needed –Oracle Server raises them implicitly ORA NO_DATA_FOUND ORA TOO_MANY_ROWS ORA ZERO_DIVIDE ORA STORAGE_ERROR ORA ACCESS_INTO_NULL ORA CASE_NOT_FOUND ORA DUP_VAL_ON_INDEX

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

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;

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

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;

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

Chapter 18: Exception Handling16 Type of RAISE Statement RAISEexception_name; RAISEPackage_name.exception; RAISE;

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

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;

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;

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;

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; ……

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

Chapter 18: Exception Handling23 1-Trapping Exceptions Syntax EXCEPTION WHEN exception1 THEN statement1; statement2; … [WHEN exception2 THEN statement1; statement2; …] [WHEN OTHERS THEN statement1; statement2; ….]

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

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

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 ;

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 …

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;

Chapter 18: Exception Handling Trapping Non_Predefined Oracle Server Errors 1.Declare the exception first 2.Code the PRAGMA EXCEPTION_INIT 3.Handle the raised exception

Chapter 18: Exception Handling30 Non-Predefined Error Syntax exceptionNameEXCEPTION; … PRAGMA EXCEPTION_INIT(exceptionName, error_No);

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;

Chapter 18: Exception Handling Trapping User_defined Exceptions 1.Declare the exception 2.Explicitly raise the exception by using RAISE statement 3.Handle the raised exception

Chapter 18: Exception Handling33 User defined Error Syntax exceptionNameEXCEPTION: … RAISE exceptionName;

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;

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

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;

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;

Chapter 18: Exception Handling38 Declarations Exception: DECLARE MaxCONSTANT NUMBER(2):=999;--exception BEGIN NULL; EXCEPTION WHEN OTHERS THEN … END; /

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;

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.

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

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;

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 ……

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;

Chapter 18: Exception Handling45 Calling a Procedure or Block to Check for Errors 1.SQL> SET SERVEROUTPUT ON SIZE FORMAT TRUNCATED 2.SQL>EXEC deposit(1111, 250, ‘check’ );

Chapter 18: Exception Handling46 Finding the Location of Errors BEGIN SELECT ….. SELECT…. EXCEPTION …….. END;

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;

Chapter 18: Exception Handling48 Method 2: Put Each Exception in a Block BEGIN SELECT ….. EXCEPTION… END; BEGIN SELECT….. EXCEPTION END;……

Chapter 18: Exception Handling49 CALL STACK V_callstack VARCHAR2(2000); BEGIN V_callstack := DBMS_UTILITY.FORMAT_CALL_STACK;

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.

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);

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;

Chapter 18: Exception Handling53 Predefined Exceptions ExceptionOracle ErrorSQLCODE Value CURSOR_ALREADY_OPENORA INVALID_CURSORORA NO_DATA_FOUNDORA SUBSCRIPT_OUTSIDE_LIMITORA SYS_INVALID_ROWIDORA TIMEOUT_ON_RESOURCEORA TOO_MANY_ROWSORA ZERO_DIVIDEORA