Содержание
- 7 Handling PL/SQL Errors
- Overview of PL/SQL Error Handling
- Advantages of PL/SQL Exceptions
- Predefined PL/SQL Exceptions
- 8 Error Handling and Diagnostics
- Why Error Handling is Needed
- Error Handling Alternatives
- SQLCA
- ORACA
- ANSI SQLSTATE Variable
- Declaring SQLSTATE
- SQLSTATE Values
- Using the SQL Communications Area
- Contents of the SQLCA
- Declaring the SQLCA
- Key Components of Error Reporting
- Status Codes
- Warning Flags
- Rows-Processed Count
- Parse Error Offset
- Error Message Text
- SQLCA Structure
- SQLCAID
- SQLCABC
- SQLCODE
- SQLERRM
- SQLERRD
- SQLWARN
- SQLEXT
- PL/SQL Considerations
- Getting the Full Text of Error Messages
- DSNTIAR
- WHENEVER Directive
- Conditions
- SQLWARNING
- SQLERROR
- NOT FOUND or NOTFOUND
- Actions
- CONTINUE
- DO CALL
- DO PERFORM
- GOTO or GO TO
- Coding the WHENEVER Statement
- DO PERFORM
- DO CALL
- Scope
- Careless Usage: Examples
- Getting the Text of SQL Statements
7
Handling PL/SQL Errors
There is nothing more exhilarating than to be shot at without result. —Winston Churchill
Run-time errors arise from design faults, coding mistakes, hardware failures, 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.
With many programming languages, unless you disable error checking, a run-time error such as stack overflow or division by zero stops normal processing and returns control to the operating system. With PL/SQL, a mechanism called exception handling lets you «bulletproof» your program so that it can continue operating in the presence of errors.
This chapter discusses the following topics:
Overview of PL/SQL Error Handling
In PL/SQL, a warning or error condition is called an exception. Exceptions can be internally defined (by the run-time system) or user defined. Examples of internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR . The other internal exceptions can be given names.
You can define exceptions of your own 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. Unlike internal exceptions, user-defined exceptions must be given names.
When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions must be raised explicitly by RAISE statements, which can also raise predefined exceptions.
To handle raised exceptions, you write separate routines called exception handlers. After an exception handler runs, the current block stops executing and the enclosing block resumes with the next statement. If there is no enclosing block, control returns to the host environment.
In the example below, you calculate and store a price-to-earnings ratio for a company with ticker symbol XYZ. If the company has zero earnings, the predefined exception ZERO_DIVIDE is raised. This stops normal execution of the block and transfers control to the exception handlers. The optional OTHERS handler catches all exceptions that the block does not name specifically.
The last example illustrates exception handling, not the effective use of INSERT statements. For example, a better way to do the insert follows:
In this example, a subquery supplies values to the INSERT statement. If earnings are zero, the function DECODE returns a null. Otherwise, DECODE returns the price-to-earnings ratio.
Advantages of PL/SQL Exceptions
Using exceptions for error handling has several advantages. Without exception handling, every time you issue a command, you must check for execution errors:
Error processing is not clearly separated from normal processing; nor is it robust. If you neglect to code a check, the error goes undetected and is likely to cause other, seemingly unrelated errors.
With exceptions, you can handle errors conveniently without the need to code multiple checks, as follows:
Exceptions improve readability by letting you isolate error-handling routines. The primary algorithm is not obscured by error recovery algorithms. Exceptions also improve reliability. You need not worry about checking for an error at every point it might occur. Just add an exception handler to your PL/SQL block. If the exception is ever raised in that block (or any sub-block), you can be sure it will be handled.
Predefined PL/SQL Exceptions
An internal exception is raised implicitly whenever your PL/SQL program violates an Oracle rule or exceeds a system-dependent limit. Every Oracle error has a number, but exceptions must be handled by name. So, PL/SQL predefines some common Oracle errors as exceptions. For example, PL/SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows.
To handle other Oracle errors, you can use the OTHERS handler. The functions SQLCODE and SQLERRM are especially useful in the OTHERS handler because they return the Oracle error code and message text. Alternatively, you can use the pragma EXCEPTION_INIT to associate exception names with Oracle error codes.
PL/SQL declares predefined exceptions globally in package STANDARD , which defines the PL/SQL environment. So, you need not declare them yourself. You can write handlers for predefined exceptions using the names in the following list:
Источник
8 Error Handling and Diagnostics
An application program must anticipate runtime errors and attempt to recover from them. This chapter provides an in-depth discussion of error reporting and recovery. You learn how to handle warnings and errors using the ANSI status variables SQLCODE and SQLSTATE, or the Oracle SQLCA (SQL Communications Area) structure. You also learn how to use the WHENEVER statement and how to diagnose problems using the Oracle ORACA (Oracle Communications Area) structure.
The following topics are discussed:
Why Error Handling is Needed
A significant part of every application program must be devoted to error handling. The main benefit of error handling is that it enables your program to continue operating in the presence of errors. Errors arise from design faults, coding mistakes, hardware failures, invalid user input, and many other sources
You cannot anticipate all possible errors, but you can plan to handle certain kinds of errors meaningful to your program. For Pro*COBOL, error handling means detecting and recovering from SQL statement execution errors. You must trap errors because the precompiler will continue regardless of the errors encountered unless you halt processing.
You can also prepare to handle warnings such as «value truncated» and status changes such as «end of data.» It is especially important to check for error and warning conditions after every data manipulation statement because an INSERT, UPDATE, or DELETE statement might fail before processing all eligible rows in a table.
Error Handling Alternatives
Pro*COBOL supports two general methods of error handling:
The Oracle-specific method with SQLCA and optional ORACA.
The SQL standard method with SQLSTATE status variable.
The precompiler MODE option governs compliance with the SQL standard. When MODE=, you declare the SQLSTATE status variable as PIC X(5). Additionally, the ANSI SQL-89 SQLCODE status variable is still supported, but it is not recommended for new programs because it has been removed from the SQL standard. When MODE=, you must include the SQLCA through an EXEC SQL INCLUDE statement. It is possible to use both methods in one program but usually not necessary.
For detailed information on mixing methods see «Status Variable Combinations».
SQLCA
The SQLCA is a record-like, host-language data structure which includes Oracle warnings, error numbers and error text. Oracle updates the SQLCA after every executable SQL or PL/SQL statement. (SQLCA values are undefined after a declarative statement.) By checking return codes stored in the SQLCA, your program can determine the outcome of a SQL statement. This can be done in two ways:
Implicit checking with the WHENEVER statement
Explicit checking of SQLCA variables
When you use the WHENEVER statement to implicitly check the status of your SQL statements, Pro*COBOL automatically inserts error checking code after each executable statement. Alternatively, you can explicitly write your own code to test the value of the SQLCODE member of the SQLCA structure. Include SQLCA by using the embedded SQL INCLUDE statement:
ORACA
When more information is needed about runtime errors than the SQLCA provides, you can use the ORACA, which contains cursor statistics, SQL statement text, certain option settings and system statistics. Include ORACA by using the embedded SQL INCLUDE statement:
The ORACA is optional and can be declared regardless of the MODE setting. For more information about the ORACA status variable, see «Using the Oracle Communications Area».
ANSI SQLSTATE Variable
When MODE=ANSI, you can declare the ANSI SQLSTATE variable inside the Declare Section for implicit or explicit error checking. If the option DECLARE_SECTION is set to NO, then you can also declare it outside of the Declare Section.
When MODE=ANSI, you can also declare the SQLCODE variable with a picture S9(9) COMP. While it can be used instead of or with the SQLSTATE variable, this is not recommended for new programs. You can also use the SQLCA with the SQLSTATE variable. When MODE=ANSI14, then SQLSTATE is not supported and you must declare either SQLCODE or include SQLCA. You cannot declare both SQLCODE and SQLCA for any setting of mode.
Declaring SQLSTATE
This section describes how to declare SQLSTATE. SQLSTATE must be declared as a five-character alphanumeric string as in the following example:
SQLSTATE Values
SQLSTATE status codes consist of a two-character class code followed by a three-character subclass code . Aside from class code 00 (successful completion), the class code denotes a category of exceptions. Aside from subclass code 000 (not applicable), the subclass code denotes a specific exception within that category. For example, the SQLSTATE value ‘22012’ consists of class code 22 (data exception) and subclass code 012 (division by zero).
Each of the five characters in a SQLSTATE value is a digit (0..9) or an uppercase Latin letter (A..Z). Class codes that begin with a digit in the range 0..4 or a letter in the range A..H are reserved for predefined conditions (those defined in the SQL standard). All other class codes are reserved for implementation-defined conditions. Within predefined classes, subclass codes that begin with a digit in the range 0..4 or a letter in the range A..H are reserved for predefined sub-conditions. All other subclass codes are reserved for implementation-defined sub-conditions. Figure 8-1 shows the coding scheme:
Figure 8-1 SQLSTATE Coding Scheme
Description of «Figure 8-1 SQLSTATE Coding Scheme»
Table 8-1 shows the classes predefined by the SQL standard.
Table 8-1 Predefined Classes
dynamic SQL error
triggered action exception
feature not supported
feature not supported
invalid target type specification
invalid schema name list specification
invalid SQL-invoked procedure reference
invalid role specification
invalid transform group name specification
target table disagrees with cursor specification
attempt to assign to non-updatable column
attempt to assign to ordering column
prohibited statement encountered during trigger execution
integrity constraint violation
invalid cursor state
invalid transaction state
invalid SQL statement name
triggered data change violation
invalid authorization specification
direct SQL syntax error or access rule violation
dependent privilege descriptors still exist
invalid character set name
invalid transaction termination
invalid connection name
SQL routine exception
invalid collation name
invalid SQL statement identifier
invalid SQL descriptor name
invalid cursor name
invalid condition number
cursor sensitivity exception
dynamic SQL syntax error or access rule violation
external routine exception
external routine invocation exception
ambiguous cursor name
invalid catalog name
invalid schema name
syntax error or access rule violation
with check option violation
remote database access
The class code HZ is reserved for conditions defined in International Standard ISO/IEC DIS 9579-2, Remote Database Access .
Table 8-4, «SQLSTATE Codes» shows how errors map to SQLSTATE status codes. In some cases, several errors map to the status code. In other cases, no error maps to the status code (so the last column is empty). Status codes in the range 60000..99999 are implementation-defined.
Using the SQL Communications Area
Oracle uses the SQL Communications Area (SQLCA) to store status information passed to your program at run time. The SQLCA is a record-like, COBOL data structure that is a updated after each executable SQL statement, so it always reflects the outcome of the most recent SQL operation. Its fields contain error, warning, and status information updated by Oracle whenever a SQL statement is executed. To determine that outcome, you can check variables in the SQLCA explicitly with your own COBOL code or implicitly with the WHENEVER statement.
When MODE=, the SQLCA is required; if the SQLCA is not declared, compile-time errors will occur. The SQLCA is optional when MODE=, but if you want to use the WHENEVER SQLWARNING statement, you must declare the SQLCA. The SQLCA must also be included when using multibyte NCHAR host variables.
When your application uses Oracle Net to access a combination of local and remote databases concurrently, all the databases write to one SQLCA. There is not a different SQLCA for each database. For more information, see «Concurrent Logons».
Contents of the SQLCA
The SQLCA contains runtime information about the execution of SQL statements, such as error codes, warning flags, event information, rows-processed count, and diagnostics.
Figure 8-2 shows all the variables in the SQLCA.
Figure 8-2 SQLCA Variable Declarations for Pro*COBOL
Description of «Figure 8-2 SQLCA Variable Declarations for Pro*COBOL»
Declaring the SQLCA
To declare the SQLCA, simply include it (using an EXEC SQL INCLUDE statement) in your Pro*COBOL source file outside the Declare Section as follows:
The SQLCA must be declared outside the Declare Section.
Do not declare SQLCODE if SQLCA is declared. Likewise, do not declare SQLCA if SQLCODE is declared. The status variable declared by the SQLCA structure is also called SQLCODE, so errors will occur if both error-reporting mechanisms are used.
When you precompile your program, the INCLUDE SQLCA statement is replaced by several variable declarations that allow Oracle to communicate with the program.
Key Components of Error Reporting
The key components of Pro*COBOL error reporting depend on several fields in the SQLCA.
Status Codes
Every executable SQL statement returns a status code in the SQLCA variable SQLCODE, which you can check implicitly with WHENEVER SQLERROR or explicitly with your own COBOL code.
Warning Flags
Warning flags are returned in the SQLCA variables SQLWARN0 through SQLWARN7, which you can check with WHENEVER SQLWARNING or with your own COBOL code. These warning flags are useful for detecting runtime conditions that are not considered errors.
Rows-Processed Count
The number of rows processed by the most recently executed SQL statement is returned in the SQLCA variable SQLERRD(3). For repeated FETCHes on an OPEN cursor, SQLERRD(3) keeps a running total of the number of rows fetched.
Parse Error Offset
Before executing a SQL statement, Oracle must parse it; that is, examine it to make sure it follows syntax rules and refers to valid database objects. If Oracle finds an error, an offset is stored in the SQLCA variable SQLERRD(5), which you can check explicitly. The offset specifies the character position in the SQL statement at which the parse error begins. The first character occupies position zero. For example, if the offset is 9, the parse error begins at the tenth character.
If your SQL statement does not cause a parse error, Oracle sets SQLERRD(5) to zero. Oracle also sets SQLERRD(5) to zero if a parse error begins at the first character (which occupies position zero). So, check SQLERRD(5) only if SQLCODE is negative, which means that an error has occurred.
Error Message Text
The error code and message for errors are available in the SQLCA variable SQLERRMC. For example, you might place the following statements in an error-handling routine:
At most, the first 70 characters of message text are stored. For messages longer than 70 characters, you must call the SQLGLM subroutine, which is discussed in «Getting the Full Text of Error Messages».
SQLCA Structure
This section describes the structure of the SQLCA, its fields, and the values they can store.
SQLCAID
This string field is initialized to «SQLCA» to identify the SQL Communications Area.
SQLCABC
This integer field holds the length, in bytes, of the SQLCA structure.
SQLCODE
This integer field holds the status code of the most recently executed SQL statement. The status code, which indicates the outcome of the SQL operation, can be any of the following numbers:
Class | Condition |
---|---|
Status Code | Description |
---|---|
Oracle executed the statement without detecting an error or exception. | |
> 0 | Oracle executed the statement but detected an exception. This occurs when Oracle cannot find a row that meets your WHERE-clause search condition or when a SELECT INTO or FETCH returns no rows. |
Oracle Database Error Messages . |
SQLERRM
This sub-record contains the following two fields:
Fields | Description |
---|---|
SQLERRML | This integer field holds the length of the message text stored in SQLERRMC. |
SQLERRMC | This string field holds the message text for the error code stored in SQLCODE and can store up to 70 characters. For the full text of messages longer than 70 characters, use the SQLGLM function. |
Verify SQLCODE is negative before you reference SQLERRMC. If you reference SQLERRMC when SQLCODE is zero, you get the message text associated with a prior SQL statement.
This string field is reserved for future use.
SQLERRD
This table of binary integers has six elements. Descriptions of the fields in SQLERRD follow:
Fields | Description |
---|---|
SQLERRD(1) | This field is reserved for future use. |
SQLERRD(2) | This field is reserved for future use. |
SQLERRD(3) | This field holds the number of rows processed by the most recently executed SQL statement. However, if the SQL statement failed, the value of SQLERRD(3) is undefined, with one exception. If the error occurred during a table operation, processing stops at the row that caused the error, so SQLERRD(3) gives the number of rows processed successfully. |
The rows-processed count is zeroed after an OPEN statement and incremented after a FETCH statement. For the EXECUTE, INSERT, UPDATE, DELETE, and SELECT INTO statements, the count reflects the number of rows processed successfully. The count does not include rows processed by an update or delete cascade. For example, if 20 rows are deleted because they meet WHERE-clause criteria, and 5 more rows are deleted because they now (after the primary delete) violate column constraints, the count is 20 not 25.
SQLERRD(4) This field is reserved for future use. SQLERRD(5) This field holds an offset that specifies the character position at which a parse error begins in the most recently executed SQL statement. The first character occupies position zero. SQLERRD(6) This field is reserved for future use.
SQLWARN
This table of single characters has eight elements. They are used as warning flags. Oracle sets a flag by assigning it a ‘W’ (for warning) character value. The flags warn of exceptional conditions.
For example, a warning flag is set when Oracle assigns a truncated column value to an output host character variable.
Figure 8-2, «SQLCA Variable Declarations for Pro*COBOL» illustrates SQLWARN implementation in Pro*COBOL as a group item with elementary PIC X items named SQLWARN0 through SQLWARN7.
Descriptions of the fields in SQLWARN follow:
Fields | Description |
---|---|
SQLWARN0 | This flag is set if another warning flag is set. |
SQLWARN1 | This flag is set if a truncated column value was assigned to an output host variable. This applies only to character data. Oracle truncates certain numeric data without setting a warning or returning a negative SQLCODE value. |
To find out if a column value was truncated and by how much, check the indicator variable associated with the output host variable. The (positive) integer returned by an indicator variable is the original length of the column value. You can increase the length of the host variable accordingly.
SQLWARN2 This flag is set if one or more NULLs were ignored in the evaluation of a SQL group function such as AVG, COUNT, or MAX. This behavior is expected because, except for COUNT(*), all group functions ignore NULLs. If necessary, you can use the SQL function NVL to temporarily assign values (zeros, for example) to the NULL column entries. SQLWARN3 This flag is set if the number of columns in a query select list does not equal the number of host variables in the INTO clause of the SELECT or FETCH statement. The number of items returned is the lesser of the two. SQLWARN4 This flag is no longer in use. SQLWARN5 This flag is set when an EXEC SQL CREATE
statement fails because of a PL/SQL compilation error. SQLWARN6 This flag is no longer in use. SQLWARN7 This flag is no longer in use.
SQLEXT
This string field is reserved for future use.
PL/SQL Considerations
When your Pro*COBOL program executes an embedded PL/SQL block, not all fields in the SQLCA are set. For example, if the block fetches several rows, the rows-processed count, SQLERRD(3), is set to 1, not the actual number of rows fetched. So, you should rely only on the SQLCODE and SQLERRM fields in the SQLCA after executing a PL/SQL block.
Getting the Full Text of Error Messages
Regardless of the setting of MODE, you can use SQLGLM to get the full text of error messages if you have explicitly declared SQLCODE and not included SQLCA. The SQLCA can accommodate error messages up to 70 characters long. To get the full text of longer (or nested) error messages, you need the SQLGLM subroutine.
If connected to a database, you can call SQLGLM using the syntax
where the parameters are:
Parameter | Datatype | Parameter Definition |
---|---|---|
MSG-TEXT | PIC X(n) | The field in which to store the error message. (Oracle blank-pads to the end of this field.) |
MAX-SIZE | PIC S9(9) COMP | An integer that specifies the maximum size of the MSG-TEXT field in bytes. |
MSG-LENGTH | PIC S9(9) COMP | An integer variable in which Oracle stores the actual length of the error message. |
All parameters must be passed by reference. This is usually the default parameter passing convention; you need not take special action.
The maximum length of an error message is 512 characters including the error code, nested messages, and message inserts such as table and column names. The maximum length of an error message returned by SQLGLM depends on the value specified for MAX-SIZE.
The following example uses SQLGLM to get an error message of up to 200 characters in length:
In the example, SQLGLM is called only when a SQL error has occurred. Always make sure SQLCODE is negative before calling SQLGLM. If you call SQLGLM when SQLCODE is zero, you get the message text associated with a prior SQL statement.
If your application calls SQLGLM to get message text, the message length must be passed. Do not use the SQLCA variable SQLERRML. SQLERRML is a PIC S9(4) COMP integer while SQLGLM and SQLIEM expect a PIC S9(9) COMP integer. Instead, use another variable declared as PIC S9(9) COMP.
DSNTIAR
DB2 provides an assembler routine called DSNTIAR to obtain a form of the SQLCA that can be displayed. For users migrating to Oracle from DB2, Pro*COBOL provides DSNTIAR. The DSNTIAR implementation is a wrapper around SQLGLM. The DSNTIAR interface is as follows
where MESSAGE is the output message area, in VARCHAR form of size greater than or equal to 240, and LRECL is a full word containing the length of the output messages, between 72 and 240. The first half-word of the MESSAGE argument contains the length of the remaining area. The possible error codes returned by DSNTIAR are listed in the following table.
Table 8-2 DSNTIAR Error Codes and Their Meanings
More data was available than could fit into the provided message
The logical record length (LRECL) was not between 72 and 240
The message area was not large enough (greater than 240)
WHENEVER Directive
By default, Pro*COBOL ignores error and warning conditions and continues processing, if possible. To do automatic condition checking and error handling, you need the WHENEVER statement.
With the WHENEVER statement you can specify actions to be taken when Oracle detects an error, warning condition, or «not found» condition. These actions include continuing with the next statement, PERFORMing a paragraph, branching to a paragraph, or stopping.
Conditions
You can have Oracle automatically check the SQLCA for any of the following conditions.
SQLWARNING
SQLWARN(0) is set because Oracle returned a warning (one of the warning flags, SQLWARN(1) through SQLWARN(7), is also set) or SQLCODE has a positive value other than +1403. For example, SQLWARN(1) is set when Oracle assigns a truncated column value to an output host variable.
Declaring the SQLCA is optional when MODE=. To use WHENEVER SQLWARNING, however, you must declare the SQLCA.
You have to have included SQLCA for this to work.
SQLERROR
SQLCODE has a negative value if Oracle returns an error.
NOT FOUND or NOTFOUND
SQLCODE has a value of +1403 (or +100 when MODE= or when END_OF_FETCH=100) when the end of fetch has been reached. This can happen when all the rows that meet the search criteria have been fetched or no rows meet that criteria.
You may use the END_OF_FETCH option to override the value use by the MODE macro option.
For more details, see «END_OF_FETCH».
Actions
You can use the WHENEVER statement to specify the following actions.
CONTINUE
Your program continues to run with the next statement if possible. This is the default action, equivalent to not using the WHENEVER statement. You can use it to «turn off» condition checking.
DO CALL
Your program calls a nested subprogram. When the end of the subprogram is reached, control transfers to the statement that follows the failed SQL statement.
DO PERFORM
Your program transfers control to a COBOL section or paragraph. When the end of the section is reached, control transfers to the statement that follows the failed SQL statement.
GOTO or GO TO
Your program branches to the specified paragraph or section.
Your program stops running and uncommitted work is rolled back.
Be careful. The STOP action displays no messages before logging off.
Though in the generated code EXEC SQL WHENEVER SQLERROR STOP is converted to IF SQLCODE IN SQLCA IS EQUAL TO 1403 THEN STOP RUN END-IF, Oracle server will take care of rolling back uncommitted data.
Coding the WHENEVER Statement
Code the WHENEVER statement using the following syntax:
DO PERFORM
When using the WHENEVER . DO PERFORM statement, the usual rules for PERFORMing a paragraph or section apply. However, you cannot use the THRU, TIMES, UNTIL, or VARYING clauses.
For example, the following WHENEVER . DO statement is invalid :
In the following example, WHENEVER SQLERROR DO PERFORM statements are used to handle specific errors:
Notice how the paragraphs check variables in the SQLCA to determine a course of action.
DO CALL
This clause calls an action subprogram. Here is the syntax of this clause:
The following restrictions or rules apply:
You cannot use the RETURNING, ON_EXCEPTION, or OVER_FLOW phrases in the USING clause.
You may have to enter the subprogram name followed by the keyword COMMON in the PROGRAM-ID statement of your COBOL source code.
You must use a WHENEVER CONTINUE statement in the action subprogram.
The action subprogram name may have to be in double quotes in the DO CALL clause of the WHENEVER directive.
Here is an example of a program that can call the error subprogram SQL-ERROR from inside the subprogram LOGON, or inside the MAIN program, without having to repeat code in two places, as when using the DO PERFORM clause:
Scope
Because WHENEVER is a declarative statement, its scope is positional, not logical. It tests all executable SQL statements that follow it in the source file, not in the flow of program logic. So, code the WHENEVER statement before the first executable SQL statement you want to test.
A WHENEVER statement stays in effect until superseded by another WHENEVER statement checking for the same condition.
Suggestion : You can place WHENEVER statements at the beginning of each program unit that contains SQL statements. That way, SQL statements in one program unit will not reference WHENEVER actions in another program unit, causing errors at compile or run time.
Careless Usage: Examples
Careless use of the WHENEVER statement can cause problems. For example, the following code enters an infinite loop if the DELETE statement sets the NOT FOUND condition, because no rows meet the search condition:
In the next example, the NOT FOUND condition is properly handled by resetting the GOTO target:
Getting the Text of SQL Statements
In many Pro*COBOL applications, it is convenient to know the text of the statement being processed, its length, and the SQL command (such as INSERT or SELECT) that it contains. This is especially true for applications that use dynamic SQL.
The routine SQLGLS, which is part of the SQLLIB runtime library, returns the following information:
The text of the most recently parsed SQL statement
The length of the statement
A function code
You can call SQLGLS after issuing a static SQL statement. With dynamic SQL Method 1, you can call SQLGLS after the SQL statement is executed. With dynamic SQL Method 2, 3, or 4, you can call SQLGLS after the statement is prepared.
To call SQLGLS, you use the following syntax:
Источник
Adblock
detector
Error Codes | Description |
---|---|
Как отлавливать ошибки в Oracle (PLSQL) EXCEPTION,SQLERRM,SQLCODE
Осваиваем Oracle и PL/SQL
Маленькое руководство по отлавливанию ошибок в Oracle PLSQL.
Описание как использовать в Oracle (PLSQL) функции SQLERRM и SQLCODE для отлова ошибок EXCEPTION, с описанием синтаксиса и примером.
Функция SQLERRM возвращает сообщение об ошибке связанное с последним возникшим исключением (ошибкой).
Функция SQLERRM — не имеет параметров.
Функция SQLCODE возвращает код ошибки связанный с последним возникшим исключением (ошибкой)
Функция SQLERRM — не имеет параметров.
Обычно обработка исключений EXCEPTION выглядит следующим образом:
EXCEPTION
WHEN наименование_ошибки_1 THEN
[statements]
WHEN наименование_ошибки_2 THEN
[statements]
WHEN наименование_ошибки_N THEN
[statements]
WHEN OTHERS THEN
[statements]
END [наименование_процедуры];
Вы можете использовать функции SQLERRM и SQLCODE для вызова сообщения об ошибке например таким образом:
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'Произошла ошибка - '||SQLCODE||' -ERROR- '||SQLERRM);
END;
-- В данном случае появится всплывающее сообщение.
Или вы можете сохранить сообщение об ошибке в таблицу таким образом:
EXCEPTION
WHEN OTHERS THEN
err_code := SQLCODE;
err_msg := SUBSTR(SQLERRM, 1, 200);
INSERT INTO error_log_table (error_time, error_number, error_message)
VALUES (sysdate, err_code, err_msg);
END;
--В данном случае ошибка будет помещена в таблицу error_log_table
Варианты основных возможных ошибок:
DUP_VAL_ON_INDEX
ORA-00001
При попытке произвести вставку INSERT или изменение UPDATE данных которое создает дублирующую запись нарушающую уникальный индекс (unique index).
TIMEOUT_ON_RESOURCE
ORA-00051
Происходит когда ресурс над которым производится операция заблокирован и произошел сброс по таймауту.
TRANSACTION_BACKED_OUT
ORA-00061
Произошёл частичный откат транзакции.
INVALID_CURSOR
ORA-01001
Попытка использовать курсор которого не существует. Может происходить если вы пытаетесь использовать FETCH курсор или закрыть CLOSE курсор до того как вы этот курсор открыли OPEN.
NOT_LOGGED_ON
ORA-01012
Попытка произвести действия не залогинившись.
LOGIN_DENIED
ORA-01017
Неудачная попытка залогиниться, в доступе отказано, не верный пользователь или пароль.
NO_DATA_FOUND
ORA-01403
Что то из перечисленного: Попытка произвести вставку SELECT INTO несуществующего набора значений (select — ничего не возвращает). Попытка доступа к неинициализированной строке/записи в таблице. Попытка чтения записи после окончания файла при помощи пакета UTL_FILE.
TOO_MANY_ROWS
ORA-01422
Попытка вставить значение в переменную при помощи SELECT INTO и select вернул более чем одно значение.
ZERO_DIVIDE
ORA-01476
Попытка деления на ноль.
INVALID_NUMBER
ORA-01722
Попытка выполнить SQL запрос который производит конвертацию строки (STRING) в число (NUMBER) при этом такое преобразование невозможно.
STORAGE_ERROR
ORA-06500
Либо нехватка памяти, либо ошибка в памяти.
PROGRAM_ERROR
ORA-06501
Внутренняя программная ошибка рекомендуется с такой ошибкой обращаться в службу поддержки Oracle.
VALUE_ERROR
ORA-06502
Попытка выполнить операцию конвертации данных которая закончилась с ошибкой (например: округление, преобразование типов, и т.п.).
CURSOR_ALREADY_OPEN
ORA-06511
Вы пытаетесь открыть курсор который уже открыт.
Вот пожалуй и всё.
Oracle
PLSQL
SQL
EXCEPTION
SQLERRM
SQLCODE
ошибки
программирование
Do you need to find out more information about your errors and exceptions in PL/SQL?
You can use the SQLCODE and SQLERRM functions to do that. Learn how the functions work and see some examples in this article.
Purpose of the SQLCODE and SQLERRM Functions
The SQLCODE function returns the number code of the most recent exception.
This number code is an ANSI-standard code, which means it is the same for all relational databases. It is different from the ORA codes, which you may also get when working with Oracle databases.
The SQLERRM function returns the error message that relates to the error number provided.
This function is similar to the SQLCODE function, where the only real useful place for it is inside an exception handler in PL/SQL. We’ll see more on this later in the article.
SQLCODE Syntax and Parameters
The SQLCODE function is pretty simple:
SQLCODE
There are no parameters for the Oracle SQLCODE function.
SQLERRM Syntax and Parameters
The syntax of this function is:
SQLERRM ( error_number )
The parameters of the SQLERRM function are:
- error_number (optional): A valid Oracle error number.
Now, it seems like a simple function, but there are some things to keep in mind:
- If the error_number is omitted, then it returns the error message associated to the current value of SQLCODE.
- If it is used outside an exception handler without a parameter, SQLERRM always returns a “normal, successful completion” message.
- The message returned begins with the Oracle error code.
- For user-defined exceptions, Oracle returns the message “user-defined exception”, unless you have specified your own message using the pragma EXCEPTION_INIT.
- If a value of 0 is used as the error_number, SQLERRM returns a “normal, successful completion” message.
- If a positive number other than 100 is used, then SQLERRM returns a “user-defined exception” message.
- If a value of 100 is used, SQLERRM returns “ORA-01403: no data found”.
How Should I Use the SQLCODE and SQLERRM Functions?
The best way to use the SQLCODE and SQLERRM functions is inside an exception handler in PL/SQL.
This is where you handle any errors that occur. If you use the SQLCODE function or SQLERRM function outside the error handler, it will return 0 and won’t be of use to you.
It’s also a good idea to assign the SQLCODE to a variable and then use that variable in your code.
The SQLERRM function is similar. It returns the error message associated with the most recent error. It is common practice to use both SQLCODE and SQLERRM together, as SQLERRM describes what the error is, but it’s up to you.
Why Am I Getting SQLERRM Invalid Identifier?
Sometimes, you might get an SQLERRM invalid identifier message in your SQL:
ORA-00904: : invalid identifier
This is often caused by a function being called that does not exist, or that needs the package to be recompiled, or the function is not accessible by the current user.
Can I Log the Line Number Using Oracle SQLERRM?
Yes, you can, but there’s no simple way to do it.
You can use the DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE); function to output the line number, which looks something like this:
ORA-06512: at line 12
Then, to store it, you’ll need to perform some string manipulation on DBMS_UTILITY.FORMAT_ERROR_BACKTRACE.
What Is The SQLERRM Length?
The maximum length of the SQLERRM function return value is 512 characters.
This is useful if you want to store the value in a table when you log an error.
This page here shows a list of many SQLCODE values. The SQLCODE of 000 is the default value and indicates success, but other messages are also not failure messages, so you shouldn’t always test for when the message is 000.
Examples of the SQLCODE Function
Here are some examples of the Oracle SQLCODE function. I find that examples are the best way for me to learn about code, even with the explanation above.
Example 1 – Output Error
This example PL/SQL code shows you how to output an error code.
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('An error was encountered: '||SQLCODE||' - '||SQLERRM);
END;
You can see that I have used the SQLCODE function as well. There is no parameter of the SQLERRM function, which means it uses the value of the SQLCODE function.
Example 2 – Raise Exception
This example PL/SQL code shows you how to raise an exception from the error that was found
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20010, 'An error was encountered: '||SQLCODE||' - '||SQLERRM);
END;
Example 3 – Insert Into Table
This example PL/SQL code shows you how to insert the error message into a table for logging purposes. You would change the value of ‘thisFunction’ to the name of the function that this code is in.
EXCEPTION
WHEN OTHERS THEN
errorcode := SQLCODE;
errormessage := SQLERRM;
INSERT INTO error_log (error_number, error_message, function_name)
VALUES (errorcode, errormessage, 'thisFunction');
END;
Example 4 – Output Specific Message
This example uses a parameter for the SQLERRM function and outputs the result.
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('An error was encountered: '||SQLERRM(-20010));
END;
You can find a full list of Oracle SQL functions here.
Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!
There is nothing more exhilarating than to be shot at without result. —Winston Churchill
Run-time errors arise from design faults, coding mistakes, hardware failures, 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.
With many programming languages, unless you disable error checking, a run-time error such as stack overflow or division by zero stops normal processing and returns control to the operating system. With PL/SQL, a mechanism called exception handling lets you «bulletproof» your program so that it can continue operating in the presence of errors.
This chapter contains these topics:
-
Overview of PL/SQL Runtime Error Handling
-
Advantages of PL/SQL Exceptions
-
Summary of Predefined PL/SQL Exceptions
-
Defining Your Own PL/SQL Exceptions
-
How PL/SQL Exceptions Are Raised
-
How PL/SQL Exceptions Propagate
-
Reraising a PL/SQL Exception
-
Handling Raised PL/SQL Exceptions
-
Tips for Handling PL/SQL Errors
-
Overview of PL/SQL Compile-Time Warnings
Overview of PL/SQL Runtime Error Handling
In PL/SQL, an error condition is called an exception. Exceptions can be internally defined (by the runtime system) or user defined. Examples of internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE
and STORAGE_ERROR
. The other internal exceptions can be given names.
You can define exceptions of your own 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. Unlike internal exceptions, user-defined exceptions must be given names.
When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions must be raised explicitly by RAISE
statements, which can also raise predefined exceptions.
To handle raised exceptions, you write separate routines called exception handlers. After an exception handler runs, the current block stops executing and the enclosing block resumes with the next statement. If there is no enclosing block, control returns to the host environment.
The following example calculates a price-to-earnings ratio for a company. If the company has zero earnings, the division operation raises the predefined exception ZERO_DIVIDE
, the execution of the block is interrupted, and control is transferred to the exception handlers. The optional OTHERS
handler catches all exceptions that the block does not name specifically.
SET SERVEROUTPUT ON; DECLARE stock_price NUMBER := 9.73; net_earnings NUMBER := 0; pe_ratio NUMBER; BEGIN -- Calculation might cause division-by-zero error. pe_ratio := stock_price / net_earnings; dbms_output.put_line('Price/earnings ratio = ' || pe_ratio); EXCEPTION -- exception handlers begin -- Only one of the WHEN blocks is executed. WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error dbms_output.put_line('Company must have had zero earnings.'); pe_ratio := null; WHEN OTHERS THEN -- handles all other errors dbms_output.put_line('Some other kind of error occurred.'); pe_ratio := null; END; -- exception handlers and block end here /
The last example illustrates exception handling. With some better error checking, we could have avoided the exception entirely, by substituting a null for the answer if the denominator was zero:
DECLARE stock_price NUMBER := 9.73; net_earnings NUMBER := 0; pe_ratio NUMBER; BEGIN pe_ratio := case net_earnings when 0 then null else stock_price / net_earnings end; END; /
Guidelines for Avoiding and Handling PL/SQL Errors and Exceptions
Because reliability is crucial for database programs, use both error checking and exception handling to ensure your program can handle all possibilities:
-
Add exception handlers whenever there is any possibility of an error occurring. Errors are especially likely during arithmetic calculations, string manipulation, and database operations. Errors could also occur at other times, for example if a hardware failure with disk storage or memory causes a problem that has nothing to do with your code; but your code still needs to take corrective action.
-
Add error-checking code whenever you can predict that an error might occur if your code gets bad input data. Expect that at some time, your code will be passed incorrect or null parameters, that your queries will return no rows or more rows than you expect.
-
Make your programs robust enough to work even if the database is not in the state you expect. For example, perhaps a table you query will have columns added or deleted, or their types changed. You can avoid such problems by declaring individual variables with
%TYPE
qualifiers, and declaring records to hold query results with%ROWTYPE
qualifiers. -
Handle named exceptions whenever possible, instead of using WHEN OTHERS in exception handlers. Learn the names and causes of the predefined exceptions. If your database operations might cause particular ORA- errors, associate names with these errors so you can write handlers for them. (You will learn how to do that later in this chapter.)
-
Test your code with different combinations of bad data to see what potential errors arise.
-
Write out debugging information in your exception handlers. You might store such information in a separate table. If so, do it by making a call to a procedure declared with the
PRAGMA AUTONOMOUS_TRANSACTION
, so that you can commit your debugging information, even if you roll back the work that the main procedure was doing. -
Carefully consider whether each exception handler should commit the transaction, roll it back, or let it continue. Remember, no matter how severe the error is, you want to leave the database in a consistent state and avoid storing any bad data.
Advantages of PL/SQL Exceptions
Using exceptions for error handling has several advantages.
With exceptions, you can reliably handle potential errors from many statements with a single exception handler:
BEGIN SELECT ... SELECT ... procedure_that_performs_select(); ... EXCEPTION WHEN NO_DATA_FOUND THEN -- catches all 'no data found' errors
Instead of checking for an error at every point it might occur, just add an exception handler to your PL/SQL block. If the exception is ever raised in that block (or any sub-block), you can be sure it will be handled.
Sometimes the error is not immediately obvious, and could not be detected until later when you perform calculations using bad data. Again, a single exception handler can trap all division-by-zero errors, bad array subscripts, and so on.
If you need to check for errors at a specific spot, you can enclose a single statement or a group of statements inside its own BEGIN-END block with its own exception handler. You can make the checking as general or as precise as you like.
Isolating error-handling routines makes the rest of the program easier to read and understand.
Summary of Predefined PL/SQL Exceptions
An internal exception is raised automatically if your PL/SQL program violates an Oracle rule or exceeds a system-dependent limit. PL/SQL predefines some common Oracle errors as exceptions. For example, PL/SQL raises the predefined exception NO_DATA_FOUND
if a SELECT
INTO
statement returns no rows.
You can use the pragma EXCEPTION_INIT
to associate exception names with other Oracle error codes that you can anticipate. To handle unexpected Oracle errors, you can use the OTHERS
handler. Within this handler, you can call the functions SQLCODE
and SQLERRM
to return the Oracle error code and message text. Once you know the error code, you can use it with pragma EXCEPTION_INIT
and write a handler specifically for that error.
PL/SQL declares predefined exceptions globally in package STANDARD
. You need not declare them yourself. You can write handlers for predefined exceptions using the names in the following list:
Exception | Oracle Error | SQLCODE Value |
---|---|---|
ACCESS_INTO_NULL |
ORA-06530 |
-6530 |
CASE_NOT_FOUND |
ORA-06592 |
-6592 |
COLLECTION_IS_NULL |
ORA-06531 |
-6531 |
CURSOR_ALREADY_OPEN |
ORA-06511 |
-6511 |
DUP_VAL_ON_INDEX |
ORA-00001 |
-1 |
INVALID_CURSOR |
ORA-01001 |
-1001 |
INVALID_NUMBER |
ORA-01722 |
-1722 |
LOGIN_DENIED |
ORA-01017 |
-1017 |
NO_DATA_FOUND |
ORA-01403 |
+100 |
NOT_LOGGED_ON |
ORA-01012 |
-1012 |
PROGRAM_ERROR |
ORA-06501 |
-6501 |
ROWTYPE_MISMATCH |
ORA-06504 |
-6504 |
SELF_IS_NULL |
ORA-30625 |
-30625 |
STORAGE_ERROR |
ORA-06500 |
-6500 |
SUBSCRIPT_BEYOND_COUNT |
ORA-06533 |
-6533 |
SUBSCRIPT_OUTSIDE_LIMIT |
ORA-06532 |
-6532 |
SYS_INVALID_ROWID |
ORA-01410 |
-1410 |
TIMEOUT_ON_RESOURCE |
ORA-00051 |
-51 |
TOO_MANY_ROWS |
ORA-01422 |
-1422 |
VALUE_ERROR |
ORA-06502 |
-6502 |
ZERO_DIVIDE |
ORA-01476 |
-1476 |
Brief descriptions of the predefined exceptions follow:
Exception | Raised when … |
---|---|
ACCESS_INTO_NULL |
A program attempts to assign values to the attributes of an uninitialized object. |
CASE_NOT_FOUND |
None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause. |
COLLECTION_IS_NULL |
A program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray. |
CURSOR_ALREADY_OPEN |
A program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers, so your program cannot open that cursor inside the loop. |
DUP_VAL_ON_INDEX |
A program attempts to store duplicate values in a database column that is constrained by a unique index. |
INVALID_CURSOR |
A program attempts a cursor operation that is not allowed, such as closing an unopened cursor. |
INVALID_NUMBER |
In a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) This exception is also raised when the LIMIT -clause expression in a bulk FETCH statement does not evaluate to a positive number. |
LOGIN_DENIED |
A program attempts to log on to Oracle with an invalid username or password. |
NO_DATA_FOUND |
A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.
Because this exception is used internally by some SQL functions to signal that they are finished, you should not rely on this exception being propagated if you raise it within a function that is called as part of a query. |
NOT_LOGGED_ON |
A program issues a database call without being connected to Oracle. |
PROGRAM_ERROR |
PL/SQL has an internal problem. |
ROWTYPE_MISMATCH |
The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. For example, when an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible. |
SELF_IS_NULL |
A program attempts to call a MEMBER method, but the instance of the object type has not been initialized. The built-in parameter SELF points to the object, and is always the first parameter passed to a MEMBER method. |
STORAGE_ERROR |
PL/SQL runs out of memory or memory has been corrupted. |
SUBSCRIPT_BEYOND_COUNT |
A program references a nested table or varray element using an index number larger than the number of elements in the collection. |
SUBSCRIPT_OUTSIDE_LIMIT |
A program references a nested table or varray element using an index number (-1 for example) that is outside the legal range. |
SYS_INVALID_ROWID |
The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid. |
TIMEOUT_ON_RESOURCE |
A time-out occurs while Oracle is waiting for a resource. |
TOO_MANY_ROWS |
A SELECT INTO statement returns more than one row. |
VALUE_ERROR |
An arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR . In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements, INVALID_NUMBER is raised.) |
ZERO_DIVIDE |
A program attempts to divide a number by zero. |
Defining Your Own PL/SQL Exceptions
PL/SQL lets you define exceptions of your own. Unlike predefined exceptions, user-defined exceptions must be declared and must be raised explicitly by RAISE
statements.
Declaring PL/SQL Exceptions
Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. You declare an exception by introducing its name, followed by the keyword EXCEPTION
. In the following example, you declare an exception named past_due
:
DECLARE past_due EXCEPTION;
Exception and variable declarations are similar. But remember, an exception is an error condition, not a data item. Unlike variables, exceptions cannot appear in assignment statements or SQL statements. However, the same scope rules apply to variables and exceptions.
Scope Rules for PL/SQL Exceptions
You cannot declare an exception twice in the same block. You can, however, declare the same exception in two different blocks.
Exceptions declared in a block are considered local to that block and global to all its sub-blocks. Because a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions declared in a sub-block.
If you redeclare a global exception in a sub-block, the local declaration prevails. The sub-block cannot reference the global exception, unless the exception is declared in a labeled block and you qualify its name with the block label:
block_label.exception_name
The following example illustrates the scope rules:
DECLARE past_due EXCEPTION; acct_num NUMBER; BEGIN DECLARE ---------- sub-block begins past_due EXCEPTION; -- this declaration prevails acct_num NUMBER; due_date DATE := SYSDATE - 1; todays_date DATE := SYSDATE; BEGIN IF due_date < todays_date THEN RAISE past_due; -- this is not handled END IF; END; ------------- sub-block ends EXCEPTION WHEN past_due THEN -- does not handle RAISEd exception dbms_output.put_line('Handling PAST_DUE exception.'); WHEN OTHERS THEN dbms_output.put_line('Could not recognize PAST_DUE_EXCEPTION in this scope.'); END; /
The enclosing block does not handle the raised exception because the declaration of past_due
in the sub-block prevails. Though they share the same name, the two past_due
exceptions are different, just as the two acct_num
variables share the same name but are different variables. Thus, the RAISE
statement and the WHEN
clause refer to different exceptions. To have the enclosing block handle the raised exception, you must remove its declaration from the sub-block or define an OTHERS
handler.
Associating a PL/SQL Exception with a Number: Pragma EXCEPTION_INIT
To handle error conditions (typically ORA-
messages) that have no predefined name, you must use the OTHERS
handler or the pragma EXCEPTION_INIT
. A pragma is a compiler directive that is processed at compile time, not at run time.
In PL/SQL, the pragma EXCEPTION_INIT
tells the compiler to associate an exception name with an Oracle error number. That lets you refer to any internal exception by name and to write a specific handler for it. When you see an error stack, or sequence of error messages, the one on top is the one that you can trap and handle.
You code the pragma EXCEPTION_INIT
in the declarative part of a PL/SQL block, subprogram, or package using the syntax
PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);
where exception_name
is the name of a previously declared exception and the number is a negative value corresponding to an ORA-
error number. The pragma must appear somewhere after the exception declaration in the same declarative section, as shown in the following example:
DECLARE deadlock_detected EXCEPTION; PRAGMA EXCEPTION_INIT(deadlock_detected, -60); BEGIN null; -- Some operation that causes an ORA-00060 error EXCEPTION WHEN deadlock_detected THEN null; -- handle the error END; /
Defining Your Own Error Messages: Procedure RAISE_APPLICATION_ERROR
The procedure RAISE_APPLICATION_ERROR
lets you issue user-defined ORA-
error messages from stored subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions.
To call RAISE_APPLICATION_ERROR
, use the syntax
raise_application_error(error_number, message[, {TRUE | FALSE}]);
where error_number
is a negative integer in the range -20000 .. -20999 and message
is a character string up to 2048 bytes long. If the optional third parameter is TRUE
, the error is placed on the stack of previous errors. If the parameter is FALSE
(the default), the error replaces all previous errors. RAISE_APPLICATION_ERROR
is part of package DBMS_STANDARD
, and as with package STANDARD
, you do not need to qualify references to it.
An application can call raise_application_error
only from an executing stored subprogram (or method). When called, raise_application_error
ends the subprogram and returns a user-defined error number and message to the application. The error number and message can be trapped like any Oracle error.
In the following example, you call raise_application_error
if an error condition of your choosing happens (in this case, if the current schema owns less than 1000 tables):
DECLARE num_tables NUMBER; BEGIN SELECT COUNT(*) INTO num_tables FROM USER_TABLES; IF num_tables < 1000 THEN /* Issue your own error code (ORA-20101) with your own error message. */ raise_application_error(-20101, 'Expecting at least 1000 tables'); ELSE NULL; -- Do the rest of the processing (for the non-error case). END IF; END; /
The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE
and SQLERRM
in an OTHERS
handler. Also, it can use the pragma EXCEPTION_INIT
to map specific error numbers returned by raise_application_error
to exceptions of its own, as the following Pro*C example shows:
EXEC SQL EXECUTE /* Execute embedded PL/SQL block using host variables my_emp_id and my_amount, which were assigned values in the host environment. */ DECLARE null_salary EXCEPTION; /* Map error number returned by raise_application_error to user-defined exception. */ PRAGMA EXCEPTION_INIT(null_salary, -20101); BEGIN raise_salary(:my_emp_id, :my_amount); EXCEPTION WHEN null_salary THEN INSERT INTO emp_audit VALUES (:my_emp_id, ...); END; END-EXEC;
This technique allows the calling application to handle error conditions in specific exception handlers.
Redeclaring Predefined Exceptions
Remember, PL/SQL declares predefined exceptions globally in package STANDARD
, so you need not declare them yourself. Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER
internally, a handler written for INVALID_NUMBER
will not catch the internal exception. In such cases, you must use dot notation to specify the predefined exception, as follows:
EXCEPTION WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN -- handle the error END;
How PL/SQL Exceptions Are Raised
Internal exceptions are raised implicitly by the run-time system, as are user-defined exceptions that you have associated with an Oracle error number using EXCEPTION_INIT
. However, other user-defined exceptions must be raised explicitly by RAISE
statements.
Raising Exceptions with the RAISE Statement
PL/SQL blocks and subprograms should raise an exception only when an error makes it undesirable or impossible to finish processing. You can place RAISE
statements for a given exception anywhere within the scope of that exception. In the following example, you alert your PL/SQL block to a user-defined exception named out_of_stock
:
DECLARE out_of_stock EXCEPTION; number_on_hand NUMBER := 0; BEGIN IF number_on_hand < 1 THEN RAISE out_of_stock; -- raise an exception that we defined END IF; EXCEPTION WHEN out_of_stock THEN -- handle the error dbms_output.put_line('Encountered out-of-stock error.'); END; /
You can also raise a predefined exception explicitly. That way, an exception handler written for the predefined exception can process other errors, as the following example shows:
DECLARE acct_type INTEGER := 7; BEGIN IF acct_type NOT IN (1, 2, 3) THEN RAISE INVALID_NUMBER; -- raise predefined exception END IF; EXCEPTION WHEN INVALID_NUMBER THEN dbms_output.put_line('Handling invalid input by rolling back.'); ROLLBACK; END; /
How PL/SQL Exceptions Propagate
When an exception is raised, if PL/SQL cannot find a handler for it in the current block or subprogram, the exception propagates. That is, the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. If no handler is found, PL/SQL returns an unhandled exception error to the host environment.
Exceptions cannot propagate across remote procedure calls done through database links. A PL/SQL block cannot catch an exception raised by a remote subprogram. For a workaround, see «Defining Your Own Error Messages: Procedure RAISE_APPLICATION_ERROR».
Figure 10-1, Figure 10-2, and Figure 10-3 illustrate the basic propagation rules.
An exception can propagate beyond its scope, that is, beyond the block in which it was declared. Consider the following example:
BEGIN DECLARE ---------- sub-block begins past_due EXCEPTION; due_date DATE := trunc(SYSDATE) - 1; todays_date DATE := trunc(SYSDATE); BEGIN IF due_date < todays_date THEN RAISE past_due; END IF; END; ------------- sub-block ends EXCEPTION WHEN OTHERS THEN ROLLBACK; END; /
Because the block that declares the exception past_due
has no handler for it, the exception propagates to the enclosing block. But the enclosing block cannot reference the name PAST_DUE
, because the scope where it was declared no longer exists. Once the exception name is lost, only an OTHERS
handler can catch the exception. If there is no handler for a user-defined exception, the calling application gets this error:
ORA-06510: PL/SQL: unhandled user-defined exception
Reraising a PL/SQL Exception
Sometimes, you want to reraise an exception, that is, handle it locally, then pass it to an enclosing block. For example, you might want to roll back a transaction in the current block, then log the error in an enclosing block.
To reraise an exception, use a RAISE
statement without an exception name, which is allowed only in an exception handler:
DECLARE salary_too_high EXCEPTION; current_salary NUMBER := 20000; max_salary NUMBER := 10000; erroneous_salary NUMBER; BEGIN BEGIN ---------- sub-block begins IF current_salary > max_salary THEN RAISE salary_too_high; -- raise the exception END IF; EXCEPTION WHEN salary_too_high THEN -- first step in handling the error dbms_output.put_line('Salary ' || erroneous_salary || ' is out of range.'); dbms_output.put_line('Maximum salary is ' || max_salary || '.'); RAISE; -- reraise the current exception END; ------------ sub-block ends EXCEPTION WHEN salary_too_high THEN -- handle the error more thoroughly erroneous_salary := current_salary; current_salary := max_salary; dbms_output.put_line('Revising salary from ' || erroneous_salary || 'to ' || current_salary || '.'); END; /
Handling Raised PL/SQL Exceptions
When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control transfers to its exception-handling part, which is formatted as follows:
EXCEPTION WHEN exception_name1 THEN -- handler sequence_of_statements1 WHEN exception_name2 THEN -- another handler sequence_of_statements2 ... WHEN OTHERS THEN -- optional handler sequence_of_statements3 END;
To catch raised exceptions, you write exception handlers. Each handler consists of a WHEN
clause, which specifies an exception, followed by a sequence of statements to be executed when that exception is raised. These statements complete execution of the block or subprogram; control does not return to where the exception was raised. In other words, you cannot resume processing where you left off.
The optional OTHERS
exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS
handler.
As the following example shows, use of the OTHERS
handler guarantees that no exception will go unhandled:
EXCEPTION WHEN ... THEN -- handle the error WHEN ... THEN -- handle the error WHEN OTHERS THEN -- handle all other errors END;
If you want two or more exceptions to execute the same sequence of statements, list the exception names in the WHEN
clause, separating them by the keyword OR
, as follows:
EXCEPTION WHEN over_limit OR under_limit OR VALUE_ERROR THEN -- handle the error
If any of the exceptions in the list is raised, the associated sequence of statements is executed. The keyword OTHERS
cannot appear in the list of exception names; it must appear by itself. You can have any number of exception handlers, and each handler can associate a list of exceptions with a sequence of statements. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram.
The usual scoping rules for PL/SQL variables apply, so you can reference local and global variables in an exception handler. However, when an exception is raised inside a cursor FOR
loop, the cursor is closed implicitly before the handler is invoked. Therefore, the values of explicit cursor attributes are not available in the handler.
Handling Exceptions Raised in Declarations
Exceptions can be raised in declarations by faulty initialization expressions. For example, the following declaration raises an exception because the constant credit_limit
cannot store numbers larger than 999:
DECLARE credit_limit CONSTANT NUMBER(3) := 5000; -- raises an exception BEGIN NULL; EXCEPTION WHEN OTHERS THEN -- Cannot catch the exception. This handler is never called. dbms_output.put_line('Can''t handle an exception in a declaration.'); END; /
Handlers in the current block cannot catch the raised exception because an exception raised in a declaration propagates immediately to the enclosing block.
Handling Exceptions Raised in Handlers
When an exception occurs within an exception handler, that same handler cannot catch the exception. An exception raised inside a handler propagates immediately to the enclosing block, which is searched to find a handler for this new exception. From there on, the exception propagates normally. For example:
EXCEPTION WHEN INVALID_NUMBER THEN INSERT INTO ... -- might raise DUP_VAL_ON_INDEX WHEN DUP_VAL_ON_INDEX THEN ... -- cannot catch the exception END;
Branching to or from an Exception Handler
A GOTO
statement can branch from an exception handler into an enclosing block.
A GOTO
statement cannot branch into an exception handler, or from an exception handler into the current block.
Retrieving the Error Code and Error Message: SQLCODE and SQLERRM
In an exception handler, you can use the built-in functions SQLCODE
and SQLERRM
to find out which error occurred and to get the associated error message. For internal exceptions, SQLCODE
returns the number of the Oracle error. The number that SQLCODE
returns is negative unless the Oracle error is no data found, in which case SQLCODE
returns +100. SQLERRM
returns the corresponding error message. The message begins with the Oracle error code.
For user-defined exceptions, SQLCODE
returns +1 and SQLERRM
returns the message: User-Defined Exception
.
unless you used the pragma EXCEPTION_INIT
to associate the exception name with an Oracle error number, in which case SQLCODE
returns that error number and SQLERRM
returns the corresponding error message. The maximum length of an Oracle error message is 512 characters including the error code, nested messages, and message inserts such as table and column names.
If no exception has been raised, SQLCODE
returns zero and SQLERRM
returns the message: ORA-0000: normal, successful completion
.
You can pass an error number to SQLERRM
, in which case SQLERRM
returns the message associated with that error number. Make sure you pass negative error numbers to SQLERRM
.
Passing a positive number to SQLERRM
always returns the message user-defined exception unless you pass +100
, in which case SQLERRM
returns the message no data found. Passing a zero to SQLERRM
always returns the message normal, successful completion.
You cannot use SQLCODE
or SQLERRM
directly in a SQL statement. Instead, you must assign their values to local variables, then use the variables in the SQL statement, as shown in the following example:
DECLARE err_msg VARCHAR2(100); BEGIN /* Get a few Oracle error messages. */ FOR err_num IN 1..3 LOOP err_msg := SUBSTR(SQLERRM(-err_num),1,100); dbms_output.put_line('Error number = ' || err_num); dbms_output.put_line('Error message = ' || err_msg); END LOOP; END; /
The string function SUBSTR
ensures that a VALUE_ERROR
exception (for truncation) is not raised when you assign the value of SQLERRM
to err_msg
. The functions SQLCODE
and SQLERRM
are especially useful in the OTHERS
exception handler because they tell you which internal exception was raised.
Note: When using pragma RESTRICT_REFERENCES
to assert the purity of a stored function, you cannot specify the constraints WNPS
and RNPS
if the function calls SQLCODE
or SQLERRM
.
Catching Unhandled Exceptions
Remember, if it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception error to the host environment, which determines the outcome. For example, in the Oracle Precompilers environment, any database changes made by a failed SQL statement or PL/SQL block are rolled back.
Unhandled exceptions can also affect subprograms. If you exit a subprogram successfully, PL/SQL assigns values to OUT
parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to OUT
parameters (unless they are NOCOPY
parameters). Also, if a stored subprogram fails with an unhandled exception, PL/SQL does not roll back database work done by the subprogram.
You can avoid unhandled exceptions by coding an OTHERS
handler at the topmost level of every PL/SQL program.
Tips for Handling PL/SQL Errors
In this section, you learn three techniques that increase flexibility.
Continuing after an Exception Is Raised
An exception handler lets you recover from an otherwise fatal error before exiting a block. But when the handler completes, the block is terminated. You cannot return to the current block from an exception handler. In the following example, if the SELECT
INTO
statement raises ZERO_DIVIDE
, you cannot resume with the INSERT
statement:
DECLARE pe_ratio NUMBER(3,1); BEGIN DELETE FROM stats WHERE symbol = 'XYZ'; SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks WHERE symbol = 'XYZ'; INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio); EXCEPTION WHEN ZERO_DIVIDE THEN NULL; END; /
You can still handle an exception for a statement, then continue with the next statement. Place the statement in its own sub-block with its own exception handlers. If an error occurs in the sub-block, a local handler can catch the exception. When the sub-block ends, the enclosing block continues to execute at the point where the sub-block ends. Consider the following example:
DECLARE pe_ratio NUMBER(3,1); BEGIN DELETE FROM stats WHERE symbol = 'XYZ'; BEGIN ---------- sub-block begins SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks WHERE symbol = 'XYZ'; EXCEPTION WHEN ZERO_DIVIDE THEN pe_ratio := 0; END; ---------- sub-block ends INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio); EXCEPTION WHEN OTHERS THEN NULL; END; /
In this example, if the SELECT
INTO
statement raises a ZERO_DIVIDE
exception, the local handler catches it and sets pe_ratio
to zero. Execution of the handler is complete, so the sub-block terminates, and execution continues with the INSERT
statement.
You can also perform a sequence of DML operations where some might fail, and process the exceptions only after the entire operation is complete, as described in «Handling FORALL Exceptions with the %BULK_EXCEPTIONS Attribute».
Retrying a Transaction
After an exception is raised, rather than abandon your transaction, you might want to retry it. The technique is:
-
Encase the transaction in a sub-block.
-
Place the sub-block inside a loop that repeats the transaction.
-
Before starting the transaction, mark a savepoint. If the transaction succeeds, commit, then exit from the loop. If the transaction fails, control transfers to the exception handler, where you roll back to the savepoint undoing any changes, then try to fix the problem.
In the following example, the INSERT
statement might raise an exception because of a duplicate value in a unique column. In that case, we change the value that needs to be unique and continue with the next loop iteration. If the INSERT succeeds, we exit from the loop immediately. With this technique, you should use a FOR
or WHILE
loop to limit the number of attempts.
DECLARE name VARCHAR2(20); ans1 VARCHAR2(3); ans2 VARCHAR2(3); ans3 VARCHAR2(3); suffix NUMBER := 1; BEGIN FOR i IN 1..10 LOOP -- try 10 times BEGIN -- sub-block begins SAVEPOINT start_transaction; -- mark a savepoint /* Remove rows from a table of survey results. */ DELETE FROM results WHERE answer1 = 'NO'; /* Add a survey respondent's name and answers. */ INSERT INTO results VALUES (name, ans1, ans2, ans3); -- raises DUP_VAL_ON_INDEX if two respondents have the same name COMMIT; EXIT; EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK TO start_transaction; -- undo changes suffix := suffix + 1; -- try to fix problem name := name || TO_CHAR(suffix); END; -- sub-block ends END LOOP; END; /
Using Locator Variables to Identify Exception Locations
Using one exception handler for a sequence of statements, such as INSERT
, DELETE
, or UPDATE
statements, can mask the statement that caused an error. If you need to know which statement failed, you can use a locator variable:
DECLARE stmt INTEGER; name VARCHAR2(100); BEGIN stmt := 1; -- designates 1st SELECT statement SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'ABC%'; stmt := 2; -- designates 2nd SELECT statement SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'XYZ%'; EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('Table name not found in query ' || stmt); END; /
Overview of PL/SQL Compile-Time Warnings
To make your programs more robust and avoid problems at run time, you can turn on checking for certain warning conditions. These conditions are not serious enough to produce an error and keep you from compiling a subprogram. They might point out something in the subprogram that produces an undefined result or might create a performance problem.
To work with PL/SQL warning messages, you use the PLSQL_WARNINGS
initialization parameter, the DBMS_WARNING
package, and the USER/DBA/ALL_PLSQL_OBJECT_SETTINGS
views.
PL/SQL Warning Categories
PL/SQL warning messages are divided into categories, so that you can suppress or display groups of similar warnings during compilation. The categories are:
Severe: Messages for conditions that might cause unexpected behavior or wrong results, such as aliasing problems with parameters.
Performance: Messages for conditions that might cause performance problems, such as passing a VARCHAR2
value to a NUMBER
column in an INSERT
statement.
Informational: Messages for conditions that do not have an effect on performance or correctness, but that you might want to change to make the code more maintainable, such as dead code that can never be executed.
The keyword All is a shorthand way to refer to all warning messages.
You can also treat particular messages as errors instead of warnings. For example, if you know that the warning message PLW-05003
represents a serious problem in your code, including 'ERROR:05003'
in the PLSQL_WARNINGS
setting makes that condition trigger an error message (PLS_05003
) instead of a warning message. An error message causes the compilation to fail.
Controlling PL/SQL Warning Messages
To let the database issue warning messages during PL/SQL compilation, you set the initialization parameter PLSQL_WARNINGS
. You can enable and disable entire categories of warnings (ALL
, SEVERE
, INFORMATIONAL
, PERFORMANCE
), enable and disable specific message numbers, and make the database treat certain warnings as compilation errors so that those conditions must be corrected.
This parameter can be set at the system level or the session level. You can also set it for a single compilation by including it as part of the ALTER PROCEDURE
statement. You might turn on all warnings during development, turn off all warnings when deploying for production, or turn on some warnings when working on a particular subprogram where you are concerned with some aspect, such as unnecessary code or performance.
ALTER SYSTEM SET PLSQL_WARNINGS='ENABLE:ALL'; -- For debugging during development. ALTER SESSION SET PLSQL_WARNINGS='ENABLE:PERFORMANCE'; -- To focus on one aspect. ALTER PROCEDURE hello COMPILE PLSQL_WARNINGS='ENABLE:PERFORMANCE'; -- Recompile with extra checking. ALTER SESSION SET PLSQL_WARNINGS='DISABLE:ALL'; -- To turn off all warnings. -- We want to hear about 'severe' warnings, don't want to hear about 'performance' -- warnings, and want PLW-06002 warnings to produce errors that halt compilation. ALTER SESSION SET PLSQL_WARNINGS='ENABLE:SEVERE','DISABLE:PERFORMANCE','ERROR:06002';
Warning messages can be issued during compilation of PL/SQL subprograms; anonymous blocks do not produce any warnings.
The settings for the PLSQL_WARNINGS
parameter are stored along with each compiled subprogram. If you recompile the subprogram with a CREATE OR REPLACE
statement, the current settings for that session are used. If you recompile the subprogram with an ALTER ... COMPILE
statement, the current session setting might be used, or the original setting that was stored with the subprogram, depending on whether you include the REUSE SETTINGS
clause in the statement.
To see any warnings generated during compilation, you use the SQL*Plus SHOW ERRORS
command or query the USER_ERRORS
data dictionary view. PL/SQL warning messages all use the prefix PLW
.
Using the DBMS_WARNING Package
If you are writing a development environment that compiles PL/SQL subprograms, you can control PL/SQL warning messages by calling subprograms in the DBMS_WARNING
package. You might also use this package when compiling a complex application, made up of several nested SQL*Plus scripts, where different warning settings apply to different subprograms. You can save the current state of the PLSQL_WARNINGS
parameter with one call to the package, change the parameter to compile a particular set of subprograms, then restore the original parameter value.
For example, here is a procedure with unnecessary code that could be removed. It could represent a mistake, or it could be intentionally hidden by a debug flag, so you might or might not want a warning message for it.
CREATE OR REPLACE PROCEDURE dead_code AS x number := 10; BEGIN if x = 10 then x := 20; else x := 100; -- dead code (never reached) end if; END dead_code;/ -- By default, the preceding procedure compiles with no errors or warnings. -- Now enable all warning messages, just for this session. CALL DBMS_WARNING.SET_WARNING_SETTING_STRING('ENABLE:ALL' ,'SESSION'); -- Check the current warning setting. select dbms_warning.get_warning_setting_string() from dual; -- When we recompile the procedure, we will see a warning about the dead code. ALTER PROCEDURE dead_code COMPILE;
See Also: ALTER PROCEDURE
, DBMS_WARNING
package in the PL/SQL Packages and Types Reference, PLW- messages in the Oracle Database Error Messages
Summary: in this tutorial, you will learn how to handle other unhandled exceptions in the WHEN OTHER
clause using SQLCODE
and SQLERRM
functions.
In this exception handling section, you can include the WHEN OTHERS
clause to catch any otherwise unhandled exceptions:
Code language: SQL (Structured Query Language) (sql)
EXCEPTION ... WHEN OTHERS -- catch other exceptions
Because you handle other non-specific exceptions in the WHEN OTHERS
clause, you will need to take advantages of the built-in error functions such as SQLCODE
and SQLERRM
.
Note that you cannot use SQLCODE
or SQLERRM
function directly in an SQL statement. Instead, you must first assign their returned values to variables, and then use the variables in the SQL statement.
SQLCODE
function
The SQLCODE
function accepts no argument and returns a number code of the most recent exception.
If the exceptions are internal, SQLCODE
returns a negative number except for the NO_DATA_FOUND
exception which has the number code +100.
If the exception is user-defined, SQLCODE
returns +1 or the number that you associated with the exception via the pragma EXCEPTION_INIT
.
The SQLCODE
is only usable in the exception-handling section. If you use the SQLCODE
function outside an exception handler, it always returns zero.
This example illustrates how to use the SQLCODE
function:
Code language: SQL (Structured Query Language) (sql)
DECLARE l_code NUMBER; r_customer customers%rowtype; BEGIN SELECT * INTO r_customer FROM customers; EXCEPTION WHEN OTHERS THEN l_code := SQLCODE; dbms_output.put_line('Error code:' || l_code); END; /
In this example, we try to fetch too many rows into a record, which results in a error with the following error code:
Code language: SQL (Structured Query Language) (sql)
Error code:-1422
SQLERRM
function
The function SQLERRM
takes an argument as an error number and returns the error message associated with that error number:
Code language: SQL (Structured Query Language) (sql)
SQLERRM([error_number])
In this syntax, the error_number
can be any valid Oracle error number.
If you omit the error_number
argument, the function will return the error message associated with the current value of SQLCODE
.
Note that the SQLERRM
function with no argument is only useful in an exception handler.
This example illustrates how to use the function SQLERRM
in an exception handler:
Code language: SQL (Structured Query Language) (sql)
DECLARE l_msg VARCHAR2(255); r_customer customers%rowtype; BEGIN SELECT * INTO r_customer FROM customers; EXCEPTION WHEN OTHERS THEN l_msg := SQLERRM; dbms_output.put_line(l_msg); END; /
Here is the output:
Code language: SQL (Structured Query Language) (sql)
ORA-01422: exact fetch returns more than requested number of rows
Using SQLCODE
and SQLERRM
functions example
The following example inserts a new contact into the contacts
table in the sample database. It has an exception handler in the WHERE OTHERS
clause of the exception handling section.
Code language: SQL (Structured Query Language) (sql)
DECLARE l_first_name contacts.first_name%TYPE := 'Flor'; l_last_name contacts.last_name%TYPE := 'Stone'; l_email contacts.email%TYPE := 'flor.stone@raytheon.com'; l_phone contacts.phone%TYPE := '+1 317 123 4105'; l_customer_id contacts.customer_id%TYPE := -1; BEGIN -- insert a new contact INSERT INTO contacts(first_name, last_name, email, phone, customer_id) VALUES(l_first_name, l_last_name, l_email, l_phone, l_customer_id); EXCEPTION WHEN OTHERS THEN DECLARE l_error PLS_INTEGER := SQLCODE; l_msg VARCHAR2(255) := sqlerrm; BEGIN CASE l_error WHEN -1 THEN -- duplicate email dbms_output.put_line('duplicate email found ' || l_email); dbms_output.put_line(l_msg); WHEN -2291 THEN -- parent key not found dbms_output.put_line('Invalid customer id ' || l_customer_id); dbms_output.put_line(l_msg); END CASE; -- reraise the current exception RAISE; END; END; /
In this example, the exception handler traps two exceptions -1 (duplicate email ) and -2291 (parent key not found). It shows a custom message and reraises the exception using the RAISE
statement.
In this tutorial, you have learned how to handle other unhandled exceptions in the WHEN OTHER
clause using the SQLCODE
and SQLERRM
functions.
Was this tutorial helpful?