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.

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

Oracle PL/SQL IV Exceptions Packages.
Chapter 4B: More Advanced PL/SQL Programming
PL/SQL Agenda: Basic PL/SQL block structure
Programming in Oracle with PL/SQL
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.
1 Agenda Summary of last class Loops Simple Loops WHILE Loops FOR Loops Records Cursors.
PL/SQL block has the following structure: DECLARE Declaration statements BEGIN Executable statements EXCEPTION Exception-handling statements END ;
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
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.
Program with PL/SQL. Interacting with the Oracle Server.
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.
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.
Manipulating Data in PL/SQL. 2 home back first prev next last What Will I Learn? Construct and execute PL/SQL statements that manipulate data with DML.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Exceptions in PL/SQL Please use speaker notes for additional information!
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.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
ITEC 224 Database Programming PL/SQL Lab Cursors.
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 
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
implicit and an explicit cursor
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the 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,
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
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.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ITEC 224 Database Programming
CHAPTER 5 EXCEPTION HANDLING
Interacting with the Oracle Server
Difference between Oracle PL/SQL and MySQL
Interacting with the Oracle Server
Handling Exceptions.
SQL Stored Triggers Presented by: Dr. Samir Tartir
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Cursors ITEC 224 Database Programming PL/SQL Lab.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Handling Exceptions.
Database Programming PL SQL.
SQL PL/SQL Presented by: Dr. Samir Tartir
Database Management Systems 2
Agenda Summary of last class Cursors Loops Records Simple Loops
Handling Exceptions.
Handling Exceptions.
Database Management Systems 2
Handling Exceptions.
PRACTICE OVERVIEW PL/SQL Part - 1.
Database Programming Using Oracle 11g
Presentation transcript:

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 run-time system) or –user-defined.

Examples of System/Oracle exceptions ORA (value string is divided by zero) and ORA (out of memory). Some common oracle exceptions have predefined names, such as –ZERO_DIVIDE and STORAGE_ERROR. The other oracle exceptions can be given names at the declaration section.

User Exceptions You can define your own exceptions in the declarative part of any PL/SQL block, subprogram, or package. For example, you might define an exception named insufficient_funds to flag overdrawn bank accounts. User-defined exceptions must be given names at the declaration section.

What happens when an error occurs? When an error occurs, an exception is raised. –Normal execution stops and control transfers to the exception-handling part of the PL/SQL block or subprogram. –Oracle/System exceptions are raised implicitly (automatically) by the run-time system. –User-defined exceptions must be raised explicitly by RAISE statements

Named system exceptions Oracle can handle: –CURSOR_ALREADY_OPENED (sqlcode = -6511) –DUP_VAL_ON_INDEX (sqlcode = -1) –INVALID_CURSOR (sqlcode = -1001) –INVALID_NUMBER (sqlcode = -1722) –LOGIN_DENIED (sqlcode = -1017) –NO_DATA_FOUND (sqlcode = +100) –TOO_MANY_ROWS (sqlcode = -1422) –…etc… These are named in the ‘standard’ package in pl/sql.

To handle these exceptions explicitly: These exception names do not need to be declared. To handle them explicitly, put a clause in the exception section: EXCEPTION When DUP_VAL_ON_INDEX dbms_output.put_line(‘record already there’); When OTHER dbms_output.put_line(‘error occurred’); END;

Unnamed system exceptions These errors are not pre-named, but have a number. They will be raised automatically by the RDBMS. The EXCEPTION section handles them in the WHEN OTHER clause. To name an unnamed error in your application: –Give the error a name using a PRAGMA, or compiler directive, called EXCEPTION_INIT. –PL/SQL or RDBMS raise the error automatically. –Handle the error in a specially written WHEN clause in the exception section.

Unnamed system exceptions We’ve all seen errors that Oracle throws at us: –ERROR: ORA=12170: TNS: Connect timeout occurred –TNS Listener does not currently know of service requested in connect descriptor Note: –All of these errors have an error number: –e.g. ORA = means that the connection timeout occurred. These errors are RAISED automatically by the system, because they are system errors.

Example DECLARE deadlock_detected EXCEPTION; PRAGMA EXCEPTION_INIT(deadlock_detected, -60); BEGIN Some operation that causes an ORA error (see locking) EXCEPTION WHEN deadlock_detected THEN -- handle the error END;

Named Programmer-Defined Exceptions Application-specific exceptions –E.g. Negative balance in account Team cannot play against itself Cannot stock a negative number of items Programmer can trap these errors and handle them. To do this: –Name the error –Check for the error and raise it –Handle the error in the EXCEPTION section

Example PROCEDURE calc_annual_sales (company_id_in IN company.company_id%TYPE) IS no_sales_for_company EXCEPTION; BEGIN -- Code here to check the number of sales -- a company has made. If none: raise no_sales_for_company; -- any other code EXCEPTION WHEN no_sales_for_company THEN dbms_output.put_line(company_id||’ has made no sales’); WHEN other THEN rollback work; END;

Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); END; /

Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement retrieved multiple rows. Consider using a cursor.'); END; /

Handling Exceptions with PL/SQL –An exception is an error PL/SQL that is raised during program execution. –An exception can be raised: Implicitly by the Oracle server Explicitly by the program –An exception can be handled: By trapping it with a handler By propagating it to the calling environment

Handling Exceptions Exception raised Is the exception trapped? yes Execute statements in the EXCEPTION section Terminate gracefully no Terminate abruptly Propagate the exception Program

Exception Types –Predefined Oracle Server –Non-predefined Oracle Server –User-defined } Implicitly raised Explicitly raised

Trapping Exceptions Syntax: EXCEPTION WHEN exception1 [OR exception2...] THEN statement1; statement2;... [WHEN exception3 [OR exception4...] THEN statement1; statement2;...] [WHEN OTHERS THEN statement1; statement2;...]

Guidelines for Trapping Exceptions –The EXCEPTION keyword starts the exception handling section. –Several exception handlers are allowed. –Only one handler is processed before leaving the block. –WHEN OTHERS is the last clause.

Trapping Predefined Oracle Server Errors –Reference the predefined name in the exception handling routine. –Sample predefined exceptions: NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE DUP_VAL_ON_INDEX

Trapping Non-Predefined Oracle Server Errors Declarative section Declare Name the exception Code PRAGMA EXCEPTION_INIT EXCEPTION section Handle the raised exception Associate Reference

SET SERVEROUTPUT ON DECLARE insert_excep EXCEPTION; PRAGMA EXCEPTION_INIT (insert_excep, ); BEGIN INSERT INTO departments (department_id, department_name) VALUES (280, NULL); EXCEPTION WHEN insert_excep THEN DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED'); DBMS_OUTPUT.PUT_LINE(SQLERRM); END; / Non-Predefined Error Trap Oracle server error number –01400, cannot insert NULL

Functions for Trapping Exceptions –SQLCODE : Returns the numeric value for the error code –SQLERRM : Returns the message associated with the error number

Functions for Trapping Exceptions Example: DECLARE error_code NUMBER; error_message VARCHAR2(255); BEGIN... EXCEPTION... WHEN OTHERS THEN ROLLBACK; error_code := SQLCODE ; error_message := SQLERRM ; INSERT INTO errors (e_user, e_date, error_code, error_message) VALUES(USER,SYSDATE,error_code, error_message); END; /

Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the RAISE statement. Exception -handling section Handle the raised exception. Raise Reference Declare

Trapping User-Defined Exceptions... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION; name VARCHAR2(20):='&name'; deptno NUMBER :=&deptno; BEGIN UPDATE departments SET department_name = name WHERE department_id = deptno; IF SQL%NOTFOUND THEN RAISE invalid_department; END IF; COMMIT; EXCEPTION WHEN invalid_department THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3

Propagating Exceptions in a Subblock DECLARE... no_rowsexception; integrityexception; PRAGMA EXCEPTION_INIT (integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT... UPDATE... IF SQL%NOTFOUND THEN RAISE no_rows; END IF; END; END LOOP; EXCEPTION WHEN integrity THEN... WHEN no_rows THEN... END; / Subblocks can handle an exception or pass the exception to the enclosing block.

The RAISE_APPLICATION_ERROR Procedure Syntax: –You can use this procedure to issue user- defined error messages from stored subprograms. –You can report errors to your application and avoid returning unhandled exceptions. raise_application_error (error_number, message[, {TRUE | FALSE}]);

The RAISE_APPLICATION_ERROR Procedure –Used in two different places: Executable section Exception section –Returns error conditions to the user in a manner consistent with other Oracle server errors.

RAISE_APPLICATION_ERROR BEGIN... DELETE FROM employees WHERE manager_id = v_mgr; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'This is not a valid manager'); END IF;... Executable section: Exception section:... EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201, 'Manager is not a valid employee.'); END; /