23
Technical Skills Enhancement – PL/SQL Best practices Exception Handling

Oracle PL/SQL exception handling

Embed Size (px)

Citation preview

Page 1: Oracle PL/SQL exception handling

Technical Skills Enhancement – PL/SQL Best practices

Exception Handling

Page 2: Oracle PL/SQL exception handling

Objectives

At the end of this training, you will be able to:

• Understand exceptions and exception handling in PL/SQL

• Use best practices in PL/SQL exception handling

Page 3: Oracle PL/SQL exception handling

Agenda– Introduction to PL/SQL exceptions

– Oracle error codes

– Pragmas

– User Defined Exception and Pragma EXCEPTION_INIT

– DBMS_UTILITY package

– Guidelines for exception handling

– Guidelines for exception handling - FORALL

– Foolproof your PL/SQL programs – Standalone procs and functions

– Foolproof your PL/SQL programs - packages

– Foolproof your PL/SQL programs - Assumptions

– Foolproof your PL/SQL programs - Tracing

Page 4: Oracle PL/SQL exception handling

Introduction to PL/SQL exceptions– All software languages have the capability to track, trap and handle

error scenarios…PL/SQL too. These error scenarios are called EXCEPTIONS

– Exceptions (when raised) generally allow the program to transfer control to

• Exception handler if one exists

• Outer (calling) program

– Exceptions arise either when the program encounters an unknown error scenario (in which case system defined exception would be raised) or a known corner case (in which case user defined exception would be raised).

– Run-time errors arise from design faults, coding mistakes, hardware failures, connection errors and many other sources. Although you cannot anticipate all possible errors, you can plan to handle certain kinds of errors meaningful to your PL/SQL program.

Page 5: Oracle PL/SQL exception handling

Introduction to exception handling

– 2 broad categories of exceptions in PL/SQL

• System defined built-in exceptionsThese exceptions are triggered by PL/SQL runtime engine implicitly.–Unnamed – Internally defined- An internally defined exception does not have a system defined name. But it has an error code. Programmer can give it a name if need be

• Eg: Error code -60 –Named – Predefined – This type of exception has an error code as well as a system defined name.

• Eg: no_data_found, too_many_rows

• User defined exceptions–These are exceptions defined by programmers in PL/SQL programs. These are declared in the DECLARE section of PL/SQL program

Page 6: Oracle PL/SQL exception handling

Introduction to exception handling

Page 7: Oracle PL/SQL exception handling

Introduction to exception handling

Exception handler

–When an exception is triggered either implicitly or explicitly the program may come to a stop abruptly and/or could produce unpredictable results. Exception handlers allow programmers to handle the known as well as unforeseen conditions gracefully.

Page 8: Oracle PL/SQL exception handling

Oracle error codes

• Oracle error codes– Oracle has 1000’s of predefined error codes

– Only a handful has predefined names, the rest have only codes

http://docs.oracle.com/cd/B28359_01/server.111/b28278/toc.htm

– Error codes from -20000 to -20999 can be used by programmers to trigger user defined errors

Page 9: Oracle PL/SQL exception handling

Pragmas

What is pragma?

•They are hints or directives to PL/SQL compiler

•It tells the compiler to perform certain actions

•There are 5 pragmas available in Oracle

•2 of them are relevant to exception handling

PRAGMA EXCEPTION_INIT: This directive binds a user defined exception to a particular error number.

PRAGMA AUTONOMOUS_TRANSACTION: This pragma can perform an autonomous transaction within a PL/SQL block between a BEGIN and END statement without affecting the entire transaction.

Page 10: Oracle PL/SQL exception handling

User Defined Exception and Pragma EXCEPTION_INITScript : Exceptions.sql

create or replace procedure get_emp_sal_raise(p_empno IN VARCHAR2) IS

empno_is_null EXCEPTION;

PRAGMA EXCEPTION_INIT(empno_is_null, -20000);

BEGIN

IF …… THEN

RAISE empno_is_null;

……………….

EXCEPTION

WHEN empno_is_null THEN

logger (message, variables, programname, linenumber);

WHEN no_data_found THEN

logger (message, variables, programname, linenumber);

WHEN OTHERS THEN

logger (message, variables, programname, linenumber);

end get_emp_sal_raise;

Page 11: Oracle PL/SQL exception handling

DBMS_UTILITY package• Oracle suggests that you stop using SQLCODE and SQLERRM

• Instead make use of new utilities from DBMS_UTILITY

• DBMS_UTILITY.FORMAT_CALL_STACK:“Where is the error in the current program?“

• DBMS_UTILITY.FORMAT_ERROR_STACK: “What was the error?”

• DBMS_UTILITY.FORMAT_ERROR_BACKTRACE: “Where in my code was the error first raised and show me the calling trail?”

BEGIN

proc3;

EXCEPTION

WHEN OTHERS

THEN

DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_stack);

DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_backtrace);

END;

Page 12: Oracle PL/SQL exception handling

Guidelines for exception handling

• Where to put DBMS_UTILITY functions

– Put them in a generic error logging and handling package. Then call the error logger from exception handlers in each program you write, passing application specific information that you will need for future debugging.

• At what level should you out exception handlers

– You must put exception handler in each block and around each DML in your block

– Handle exceptions right then and there.

– It is more work for the developer, but it has several benefits• Local variables can be tracked

• Less scenarios and combinations to think about and handle in smaller blocks

• Etc etc…..

Page 13: Oracle PL/SQL exception handling

Guidelines for exception handling - FORALL

Script : Exceptions_FORALL.sql

•FORALL provides improved performance through bulk processing several DML statements

•But when an exception occurs in one of those statements, that statement is rolled back and execution of FORALL stops.

•The subsequent DML statements are aborted.

•This may not be the desired result. In some cases you might want to continue execution of FORALL despite errors in the middle.

•Use SAVE EXCEPTIONS !!

Page 14: Oracle PL/SQL exception handling

Guidelines for exception handling - FORALL

• When you use SAVE EXCEPTIONS, it allows all DML statements to complete, except the ones that failed, of course !.

• If there are failed statements, Oracle will raise ORA-24381 immediately after FORALL. This is a system defined unnamed exception.

• Information about each failed statement can be obtained from the implicit cursor attribute SQL%BULK_EXCEPTIONS

• SQL%BULK_EXCEPTIONS is an associative array containing the following attributes– SQL%BULK_EXCEPTIONS.COUNT: The number of DML statements that

failed

– SQL%BULK_EXCEPTIONS(i).ERROR_INDEX: The number of the DML statement that failed.

– SQL%BULK_EXCEPTIONS(i).ERROR_CODE: The Oracle Database error code for the failure.

Page 15: Oracle PL/SQL exception handling

Foolproof your PL/SQL programs – Standalone procs and functions

• Every block of PL/SQL code in your project should have the same structure:

– Declaration, Execution, Exception

• Use nested subprograms– Private Programs within procedures

and functions.

– A great way to structure your code to

make it more readable and maintainable.

Page 16: Oracle PL/SQL exception handling

Foolproof your PL/SQL programs - packages

Page 17: Oracle PL/SQL exception handling

Foolproof your PL/SQL programs - Assumptions

• Avoid making assumptions in your code. It makes it hard to diagnose issues when the program breaks down.

• Always think about all possible scenarios and write code that would work in all possible scenarios.

• All programs must validate inputs through a standard and generic assertion program built for the project.

Page 18: Oracle PL/SQL exception handling

Foolproof your PL/SQL programs - Assumptions

• Avoid making assumptions in your code. It makes it hard to diagnose issues when the program breaks down.

• Always think about all possible scenarios and write code that would work in all possible scenarios.

• All programs must validate inputs through a standard and generic assertion program built for the project.

Page 19: Oracle PL/SQL exception handling

Foolproof your PL/SQL programs - Tracing

• Never put calls to DBMS_OUTPUT.PUT_LINE in your application code, not even for debugging. Instead log to tables

• Do not comment out tracing when moving to production. Instead have them driven by a boolean switch.

• Use a standard and generic logging program in all PL/SQL programs.

Page 20: Oracle PL/SQL exception handling

Guidelines for exception handling• Decide about exception handling before starting the application

development. Some recommendations:

• Decide and standardize the use of• RAISE_APPLICATION_ERROR • PRAGMA EXCEPTION_INIT, • explicit (hard-coded) -20,NNN error numbers,

• ENCOURAGE use of – standardized components, – including programs to raise application-specific exception, – handle (log, re-raise, etc.) errors, and – rely on pre-defined error numbers and messages.

• DISCOURAGE individual developer usage of – hard-coded error messages, – exposed exception handling logic.

Page 21: Oracle PL/SQL exception handling

Guidelines for exception handling

• Create checklists to serve as reminders be fo re construction, and guidelines for code review a fte r completion

• General coding guidelines– All naming conventions are followed– No hard-coded values– Repetitive code is modularized– Functions always return values– Unused variables and code sections must be removed– Functions that are executed repeatedly must be tuned – Ensure that code takes advantage of newer features of

the language.

Page 22: Oracle PL/SQL exception handling

Guidelines for exception handling• Standards should be set before coding

– It's not the kind of thing you can easily add in later

• Standard exception handling procedures need to be developed– Everyone and all programs need to handle errors the same way

• Any errors that can be generated by the program should be caught by an exception handler. If an exception propagates out of the outermost block, then the exception goes unhandled and an automatic rollback occurs.

• Define savepoints in program. To avoid automatic rollback, handle the exceptions and explicitly ROLLBACK to a savepoint.

• Collect as much information as possible of the error and log them to table

Page 23: Oracle PL/SQL exception handling

Thank YouFeedback, Questions, Discussion