handling exceptions

32
Handling Handling Exceptions Exceptions

Upload: thane-bruce

Post on 01-Jan-2016

30 views

Category:

Documents


0 download

DESCRIPTION

Handling Exceptions. Handling Exceptions with PL/SQL. What is an exception? Identifier in PL/SQL that is raised during execution How is it raised? An Oracle error occurs. You raise it explicitly. How do you handle it? Trap it with a handler. Propagate it to the calling environment. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Handling Exceptions

Handling ExceptionsHandling ExceptionsHandling ExceptionsHandling Exceptions

Page 2: Handling Exceptions

Handling Exceptions with Handling Exceptions with PL/SQLPL/SQL

Handling Exceptions with Handling Exceptions with PL/SQLPL/SQL What is an exception?What is an exception?

• Identifier in PL/SQL that is raised during Identifier in PL/SQL that is raised during executionexecution

How is it raised?How is it raised?• An Oracle error occurs.An Oracle error occurs.• You raise it explicitly.You raise it explicitly.

How do you handle it?How do you handle it?• Trap it with a handler.Trap it with a handler.• Propagate it to the calling environment.Propagate it to the calling environment.

What is an exception?What is an exception?• Identifier in PL/SQL that is raised during Identifier in PL/SQL that is raised during

executionexecution How is it raised?How is it raised?

• An Oracle error occurs.An Oracle error occurs.• You raise it explicitly.You raise it explicitly.

How do you handle it?How do you handle it?• Trap it with a handler.Trap it with a handler.• Propagate it to the calling environment.Propagate it to the calling environment.

Page 3: Handling Exceptions

Handling ExceptionsHandling ExceptionsHandling ExceptionsHandling Exceptions

Trap the Trap the exceptionexceptionDECLAREDECLARE

BEGINBEGIN

END;END;

Exception Exception is raisedis raised

EXCEPTIONEXCEPTION

Exception Exception is trappedis trapped

Propagate the exceptionPropagate the exception

DECLAREDECLARE

BEGINBEGIN

END;END;

Exception Exception is raisedis raised

EXCEPTIONEXCEPTION

Exception isException isnot trappednot trapped

Exception Exception propagates to calling propagates to calling

environmentenvironment

Page 4: Handling Exceptions

Exception TypesException TypesException TypesException Types

Predefined Oracle ServerPredefined Oracle Server Non-predefined Oracle ServerNon-predefined Oracle Server User-definedUser-defined

Predefined Oracle ServerPredefined Oracle Server Non-predefined Oracle ServerNon-predefined Oracle Server User-definedUser-defined

}} Implicitly Implicitly raisedraised

Explicitly raisedExplicitly raised

Page 5: Handling Exceptions

Trapping ExceptionsTrapping ExceptionsTrapping ExceptionsTrapping Exceptions

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

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

SyntaxSyntax SyntaxSyntax

Page 6: Handling Exceptions

Trapping Exceptions GuidelinesTrapping Exceptions GuidelinesTrapping Exceptions GuidelinesTrapping Exceptions Guidelines

WHEN OTHERS is the last clause.WHEN OTHERS is the last clause. EXCEPTION keyword starts exception-EXCEPTION keyword starts exception-

handling section.handling section. Several exception handlers are allowed.Several exception handlers are allowed. Only one handler is processed before Only one handler is processed before

leaving the block.leaving the block.

WHEN OTHERS is the last clause.WHEN OTHERS is the last clause. EXCEPTION keyword starts exception-EXCEPTION keyword starts exception-

handling section.handling section. Several exception handlers are allowed.Several exception handlers are allowed. Only one handler is processed before Only one handler is processed before

leaving the block.leaving the block.

Page 7: Handling Exceptions

Trapping Predefined Trapping Predefined Oracle Server ErrorsOracle Server ErrorsTrapping Predefined Trapping Predefined Oracle Server ErrorsOracle Server Errors

Reference the standard name in the Reference the standard name in the exception-handling routine.exception-handling routine.

Sample predefined exceptions: Sample predefined exceptions: • NO_DATA_FOUNDNO_DATA_FOUND• TOO_MANY_ROWSTOO_MANY_ROWS• INVALID_CURSORINVALID_CURSOR• ZERO_DIVIDEZERO_DIVIDE• DUP_VAL_ON_INDEXDUP_VAL_ON_INDEX

Reference the standard name in the Reference the standard name in the exception-handling routine.exception-handling routine.

Sample predefined exceptions: Sample predefined exceptions: • NO_DATA_FOUNDNO_DATA_FOUND• TOO_MANY_ROWSTOO_MANY_ROWS• INVALID_CURSORINVALID_CURSOR• ZERO_DIVIDEZERO_DIVIDE• DUP_VAL_ON_INDEXDUP_VAL_ON_INDEX

Page 8: Handling Exceptions

Predefined ExceptionPredefined ExceptionPredefined ExceptionPredefined Exception

BEGIN SELECT ... COMMIT;EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3;END;

SyntaxSyntax SyntaxSyntax

Page 9: Handling Exceptions

Trapping Non-Predefined Trapping Non-Predefined Oracle Server ErrorsOracle Server Errors

Trapping Non-Predefined Trapping Non-Predefined Oracle Server ErrorsOracle Server Errors

DeclareDeclare

• Name the Name the exceptionexception

AssociateAssociate

• Code the PRAGMA Code the PRAGMA EXCEPTION_INITEXCEPTION_INIT

Declarative sectionDeclarative section

Reference Reference

• Handle the Handle the raised raised exceptionexception

Exception-handlingException-handlingsectionsection

Page 10: Handling Exceptions

DECLARE e_emps_remaining EXCEPTION; PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno;BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT;EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. ');END;

DECLARE e_emps_remaining EXCEPTION; PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno;BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT;EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. ');END;

Non-Predefined ErrorNon-Predefined ErrorNon-Predefined ErrorNon-Predefined Error Trap for Oracle Server error number Trap for Oracle Server error number

–2292, an integrity constraint 2292, an integrity constraint violation.violation.

Trap for Oracle Server error number Trap for Oracle Server error number –2292, an integrity constraint 2292, an integrity constraint violation.violation.

e_emps_remaining EXCEPTION; 1PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292); 2

e_emps_remaining 3

Page 11: Handling Exceptions

Trapping User-Defined Trapping User-Defined ExceptionsExceptions

Trapping User-Defined Trapping User-Defined ExceptionsExceptions

• Name the Name the exceptionexception

DeclareDeclare

DeclarativeDeclarativesectionsection

RaiseRaise

• Explicitly raise Explicitly raise the exception by the exception by using the RAISE using the RAISE statementstatement

ExecutableExecutablesectionsection

Reference Reference

• Handle the Handle the raised raised exceptionexception

Exception-handlingException-handlingsectionsection

Page 12: Handling Exceptions

User-Defined ExceptionUser-Defined ExceptionUser-Defined ExceptionUser-Defined Exception

DECLARE e_invalid_product EXCEPTION;BEGIN UPDATE product SET descrip = '&product_description' WHERE prodid = &product_number; IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT;EXCEPTION WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.');END;

DECLARE e_invalid_product EXCEPTION;BEGIN UPDATE product SET descrip = '&product_description' WHERE prodid = &product_number; IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT;EXCEPTION WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.');END;

ExampleExampleExampleExample

e_invalid_product EXCEPTION; 1

RAISE e_invalid_product; 2

e_invalid_product 3

Page 13: Handling Exceptions

Functions for Trapping Functions for Trapping ExceptionsExceptions

Functions for Trapping Functions for Trapping ExceptionsExceptions

SQLCODESQLCODEReturns the numeric value for the error codeReturns the numeric value for the error code

SQLERRMSQLERRMReturns the message associated with the error Returns the message associated with the error numbernumber

SQLCODESQLCODEReturns the numeric value for the error codeReturns the numeric value for the error code

SQLERRMSQLERRMReturns the message associated with the error Returns the message associated with the error numbernumber

Page 14: Handling Exceptions

Functions for Trapping Functions for Trapping ExceptionsExceptions

Functions for Trapping Functions for Trapping ExceptionsExceptions

DECLARE v_error_code NUMBER; v_error_message VARCHAR2(255);BEGIN...EXCEPTION... WHEN OTHERS THEN ROLLBACK; v_error_code := SQLCODE ; v_error_message := SQLERRM ;

INSERT INTO errors VALUES(v_error_code, v_error_message);

END;

ExampleExample ExampleExample

SQLCODESQLERRM

Page 15: Handling Exceptions

Calling EnvironmentsCalling EnvironmentsCalling EnvironmentsCalling EnvironmentsSQL*Plus

Procedure Builder

OracleDeveloperForms

Precompilerapplication

An enclosing PL/SQL block

Displays error number and message to screen

Displays error number and message to screen

Accesses error number and message

in a trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions

Accesses exception number throughthe SQLCA data structure

Traps exception in exception-handling routine of enclosing block

Page 16: Handling Exceptions

Propagating ExceptionsPropagating ExceptionsPropagating ExceptionsPropagating Exceptions

BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE e_no_rows; END IF;EXCEPTION WHEN e_integrity THEN ... WHEN e_no_rows THEN ...END;

DECLARE . . . e_no_rows exception; e_integrity exception; PRAGMA EXCEPTION_INIT (e_integrity, -2292);BEGIN FOR c_record IN emp_cursor LOOP

END LOOP;EXCEPTION WHEN NO_DATA_FOUND THEN . . . WHEN TOO_MANY_ROWS THEN . . .END;

Subblocks can handle Subblocks can handle an exception or pass an exception or pass the exception to the the exception to the enclosing block.enclosing block.

BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE e_no_rows; END IF;EXCEPTION WHEN e_integrity THEN ... WHEN e_no_rows THEN ...END;

Page 17: Handling Exceptions

RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERRORProcedureProcedure

RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERRORProcedureProcedure

SyntaxSyntax

A procedure that lets you issue user-A procedure that lets you issue user-defined error messages from stored defined error messages from stored subprogramssubprograms

Called only from an executing stored Called only from an executing stored subprogramsubprogram

SyntaxSyntax

A procedure that lets you issue user-A procedure that lets you issue user-defined error messages from stored defined error messages from stored subprogramssubprograms

Called only from an executing stored Called only from an executing stored subprogramsubprogram

raise_application_error (error_number,message[, {TRUE | FALSE}]);

raise_application_error (error_number,message[, {TRUE | FALSE}]);

Page 18: Handling Exceptions

RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERRORProcedureProcedure

RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERRORProcedureProcedure

Used in two different places:Used in two different places:• Executable sectionExecutable section• Exception sectionException section

Returns error conditions to the user in a Returns error conditions to the user in a manner consistent with other Oracle manner consistent with other Oracle Server errorsServer errors

Used in two different places:Used in two different places:• Executable sectionExecutable section• Exception sectionException section

Returns error conditions to the user in a Returns error conditions to the user in a manner consistent with other Oracle manner consistent with other Oracle Server errorsServer errors

Page 19: Handling Exceptions

Creating ProceduresCreating ProceduresCreating ProceduresCreating Procedures

Page 20: Handling Exceptions

Overview of ProceduresOverview of ProceduresOverview of ProceduresOverview of Procedures

A procedure is a named PL/SQL block A procedure is a named PL/SQL block that performs an action.that performs an action.

A procedure can be stored in the A procedure can be stored in the database, as a database object, for database, as a database object, for repeated execution.repeated execution.

A procedure is a named PL/SQL block A procedure is a named PL/SQL block that performs an action.that performs an action.

A procedure can be stored in the A procedure can be stored in the database, as a database object, for database, as a database object, for repeated execution.repeated execution.

Page 21: Handling Exceptions

Syntax for Creating ProceduresSyntax for Creating ProceduresSyntax for Creating ProceduresSyntax for Creating Procedures

CREATE [OR REPLACE] PROCEDURE procedure_name (argument1 [mode1] datatype1, argument2 [mode2] datatype2, . . .IS [AS]PL/SQL Block;

CREATE [OR REPLACE] PROCEDURE procedure_name (argument1 [mode1] datatype1, argument2 [mode2] datatype2, . . .IS [AS]PL/SQL Block;

Page 22: Handling Exceptions

Procedural Parameter ModesProcedural Parameter ModesProcedural Parameter ModesProcedural Parameter Modes

CallingCallingenvironmentenvironment

ProcedureProcedure

(DECLARE)(DECLARE)

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

IN parameterIN parameter

OUT parameter OUT parameter

IN OUT parameterIN OUT parameter

Page 23: Handling Exceptions

IN OUT

Must be specified

Passed into subprogram; returned to calling environment

Initialized variable

Must be a variable

OUT

Must be specified

Returned to calling environment

Uninitialized variable

Must be a variable

Parameter Modes for Formal Parameter Modes for Formal ParametersParameters

Parameter Modes for Formal Parameter Modes for Formal ParametersParameters

IN

Default

Value ispassed into subprogram

Formal parameter acts as a constant

Actual parametercan be a literal, expression, constant, orinitialized variable

Page 24: Handling Exceptions

IN Parameters: ExampleIN Parameters: ExampleIN Parameters: ExampleIN Parameters: Example

SQL> CREATE OR REPLACE PROCEDURE raise_salary 2 (v_id in emp.empno%TYPE) 3 IS 4 BEGIN 5 UPDATE emp 6 SET sal = sal * 1.10 7 WHERE empno = v_id; 8 END raise_salary; 9 /Procedure created.Procedure created.

SQL> EXECUTE raise_salary (7369)PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

SQL> CREATE OR REPLACE PROCEDURE raise_salary 2 (v_id in emp.empno%TYPE) 3 IS 4 BEGIN 5 UPDATE emp 6 SET sal = sal * 1.10 7 WHERE empno = v_id; 8 END raise_salary; 9 /Procedure created.Procedure created.

SQL> EXECUTE raise_salary (7369)PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

v_idv_id73697369

Page 25: Handling Exceptions

OUT Parameters: ExampleOUT Parameters: ExampleOUT Parameters: ExampleOUT Parameters: Example

Calling environmentCalling environment QUERY_EMP procedureQUERY_EMP procedure

76547654 v_idv_id

v_namev_name

v_salaryv_salary

v_ commv_ comm

MARTINMARTIN

12501250

14001400

Page 26: Handling Exceptions

IN OUT ParametersIN OUT ParametersIN OUT ParametersIN OUT Parameters

SQL> CREATE OR REPLACE PROCEDURE format_phone 2 (v_phone_no IN OUT VARCHAR2) 3 IS 4 BEGIN 5 v_phone_no := '(' || SUBSTR(v_phone_no,1,3) || 6 ')' || SUBSTR(v_phone_no,4,3) || 7 '-' || SUBSTR(v_phone_no,7); 8 END format_phone; 9 /

Calling environmentCalling environment FORMAT_PHONE procedureFORMAT_PHONE procedure

v_phone_nov_phone_no'(800)633-0575' '(800)633-0575' '(800)633-0575' '(800)633-0575'

Page 27: Handling Exceptions

Invoking a Procedure from an Invoking a Procedure from an Anonymous PL/SQL BlockAnonymous PL/SQL Block

Invoking a Procedure from an Invoking a Procedure from an Anonymous PL/SQL BlockAnonymous PL/SQL Block

DECLARE v_id NUMBER := 7900;BEGIN raise_salary(v_id); --invoke procedureCOMMIT;...

END;

DECLARE v_id NUMBER := 7900;BEGIN raise_salary(v_id); --invoke procedureCOMMIT;...

END;

Page 28: Handling Exceptions

Invoking a Procedure from a Invoking a Procedure from a Stored ProcedureStored Procedure

Invoking a Procedure from a Invoking a Procedure from a Stored ProcedureStored Procedure

SQL> CREATE OR REPLACE PROCEDURE process_emps 2 IS 3 CURSOR emp_cursor IS 4 SELECT empno 5 FROM emp; 6 BEGIN 7 FOR emp_rec IN emp_cursor LOOP 8 raise_salary(emp_rec.empno); --invoke procedure 9 END LOOP; 10 COMMIT; 11 END process_emps; 12 /

SQL> CREATE OR REPLACE PROCEDURE process_emps 2 IS 3 CURSOR emp_cursor IS 4 SELECT empno 5 FROM emp; 6 BEGIN 7 FOR emp_rec IN emp_cursor LOOP 8 raise_salary(emp_rec.empno); --invoke procedure 9 END LOOP; 10 COMMIT; 11 END process_emps; 12 /

Page 29: Handling Exceptions

Removing ProceduresRemoving ProceduresRemoving ProceduresRemoving Procedures

Using SQL*Plus:Using SQL*Plus:

Drop a server-side procedureDrop a server-side procedure

Using SQL*Plus:Using SQL*Plus:

Drop a server-side procedureDrop a server-side procedure

Page 30: Handling Exceptions

Removing Server-Side Removing Server-Side ProceduresProcedures

Removing Server-Side Removing Server-Side ProceduresProcedures

Using SQL*Plus:Using SQL*Plus: SyntaxSyntax

ExampleExample

Using SQL*Plus:Using SQL*Plus: SyntaxSyntax

ExampleExample

DROP PROCEDURE procedure_nameDROP PROCEDURE procedure_name

SQL> DROP PROCEDURE raise_salary;Procedure dropped.

SQL> DROP PROCEDURE raise_salary;Procedure dropped.

Page 31: Handling Exceptions

SummarySummarySummarySummary

Exception types:Exception types:• Predefined Oracle Server errorPredefined Oracle Server error• Non-predefined Oracle Server errorNon-predefined Oracle Server error• User-defined errorUser-defined error

Exception trappingException trapping Exception handling:Exception handling:

• Trap the exception within the PL/SQL block.Trap the exception within the PL/SQL block.

• Propagate the exception.Propagate the exception.

Exception types:Exception types:• Predefined Oracle Server errorPredefined Oracle Server error• Non-predefined Oracle Server errorNon-predefined Oracle Server error• User-defined errorUser-defined error

Exception trappingException trapping Exception handling:Exception handling:

• Trap the exception within the PL/SQL block.Trap the exception within the PL/SQL block.

• Propagate the exception.Propagate the exception.

Page 32: Handling Exceptions

SummarySummarySummarySummary

A procedure is a named PL/SQL block A procedure is a named PL/SQL block that performs an action.that performs an action.

Use parameters to pass data from the Use parameters to pass data from the calling environment to the procedure.calling environment to the procedure.

Procedures can be invoked from any Procedures can be invoked from any tool or language that supports PL/SQL.tool or language that supports PL/SQL.

Procedures can serve as building blocks Procedures can serve as building blocks for an application.for an application.

A procedure is a named PL/SQL block A procedure is a named PL/SQL block that performs an action.that performs an action.

Use parameters to pass data from the Use parameters to pass data from the calling environment to the procedure.calling environment to the procedure.

Procedures can be invoked from any Procedures can be invoked from any tool or language that supports PL/SQL.tool or language that supports PL/SQL.

Procedures can serve as building blocks Procedures can serve as building blocks for an application.for an application.