The meaning of the various error message prefixes doesn’t seem to be clearly explained in the documentation. They are grouped in the error message manual but it doesn’t really say what each group relates to — though you can usually work it out from the messages themselves.
But you’re broadly right; at least that PLS errors are related to PL/SQL. ORA errors cover a wide spectrum and many of them can be because of ‘programming’ errors, depending on how you define that.
The error messages introducton says:
All messages displayed are prefixed by text that indicates which
program issued the message. For example, the prefix «ORA» shows that
the message was generated by the Oracle products.
Since this is the Oracle documentation, saying the errors are generated by Oracle products doesn’t add much, and the non-ORA codes come from Oracle products too.
The SQL*Plus user guide includes a slightly more relevant summary:
If the error is a numbered error beginning with the letters «ORA»,
look up the Oracle Database message in the Oracle Database Error
Messages guide or in the platform-specific Oracle documentation
provided for your operating system.If the error is a numbered error beginning with the letters «PLS»,
look up the Oracle Database message in the Oracle Database PL/SQL
Language Reference.
… although the PLS errors are not in a separate document so that looks like a doc bug. The main error documentation includes both core ORA errors and many other prefixes from specific products, including PLS errors, and also notes that ‘messages are specific to one product and are documented in manuals for that product’.
If you go back to the Oracle 9i error messages you can see a description of that the prefixes mean — PLS is ‘PL/SQL and FIPS Messages’ according to that. It isn’t in later releases — maybe the lines between products were too blurred for it to be meaningful. I suspect it’s largely down to which group has responsibility for assigning the messages to the codes for a product, and to some extent maybe has historic significance where products were acquired and adapted into the Oracle portfolio (as I believe PL/SQL itself was originally).
The oerr
tool’s usage statement calls the prefix a ‘facility’, which doesn’t help much either.
If you see a PLS error then it doesn’t even have to come from PL/SQL code you’ve written, or from a PL/SQL block. You can call a function from SQL that can get a PLS error, since they are (usually) implemented in PL/SQL. And you can get an ORA error while compiling PL/SQL.
So I’m not sure the distinction is entirely clear, but it’s also not very useful. Whichever prefix your error has, you can look it up in the error messages book and see what it means and how to resolve it
Предупреждения во время компиляции способны существенно упростить сопровождение вашего кода и снизить вероятность ошибок. Не путайте предупреждения компилятора с ошибками; с предупреждениями ваша программа все равно будет компилироваться и работать. Тем не менее при выполнения кода, для которого выдавались предупреждения, возможно неожиданное поведение или снижение производительности.
В этой заметке моего блога вы узнаете, как работают предупреждения компилятора и какие проблемы выявляются в текущих версиях. Начнем с краткого примера применения предупреждений времени компиляции в сеансе.
Пример
Очень полезное предупреждением компилятора PLW-06002
сообщает о наличии недостижимого кода. Рассмотрим следующую программу. Так как переменная salary
инициализируется значением 10 000, условная команда всегда будет отправлять меня на строку 9. Строка 7 выполняться не будет:
1 PROCEDURE cant_go_there
2 AS
3 l_salary NUMBER := 10000;
4 BEGIN
5 IF l_salary > 20000
6 THEN
7 DBMS_OUTPUT.put_line ('Executive');
8 ELSE
9 DBMS_OUTPUT.put_line ('Rest of Us');
10 END IF;
11 END cant_go_there;
Если откомпилировать этот код в любой версии до Oracle Database 10g
, компилятор просто сообщит о том, что процедура создана. Но если включить предупреждения компиляции в сеансе этой или более поздней версии, то при попытке откомпилировать процедуру будет получен следующий ответ от компилятора:
SP2-0804: Procedure created with compilation warnings
SQL> SHOW err
Errors for PROCEDURE CANT GO THERE:
LINE/COL ERROR
-------- -----------------------
7/7 PLW-06002: Unreachable code
С этим предупреждением я могу вернуться к указанной строке, определить, почему она недостижима, и внести необходимые исправления.
Включение предупреждений компилятора PL/SQL
Oracle позволяет включать и отключать предупреждения компилятора, а также указывать, какие виды предупреждений представляют интерес. Предупреждения делятся на три категории:
- Критичные — ситуации, которые могут привести к неожиданному поведению или получению неверных результатов (как, например, проблемы с псевдонимами параметров).
- Производительные — ситуации, способные вызвать проблемы с производительностью (например, указание значения
VARCHAR2
для столбцаNUMBER
в командеUPDATE
). - Информационные — ситуации, не влияющие на производительность или правильность выполнения кода, но которые стоит изменить ради того, чтобы упростить сопровождение.
Oracle позволяет включать и отключать предупреждения конкретной категории, всех категорий и даже конкретные предупреждения. Для этого используется команда ALTER DDL
или встроенный пакет DBMS_WARNING
.
Следующая команда включает предупреждения компиляции для системы в целом:
ALTER SYSTEM SET PLSQL_WARNINGS='string'
А следующая команда, например, включает предупреждения в вашей системе для всех категорий:
ALTER SYSTEM SET PLSQL_WARNINGS='ENABLE:ALL';
Это значение особенно полезно во время разработки, потому что оно позволит обнаружить наибольшее количество потенциальных проблем в вашем коде.
Чтобы включить предупреждения в сеансе только для критичных проблем, введите следующую команду:
ALTER SESSION SET PLSQL_WARNINGS='ENABLE:SEVERE';
А для изменения настройки предупреждений компилятора для конкретной, уже откомпилированной программы вводится команда следующего вида:
ALTER PROCEDURE hello COMPILE PLSQL_WARNINGS='ENABLE:ALL' REUSE SETTINGS;
Обязательно включите секцию REUSE SETTINGS
, чтобы команда ALTER
не влияла на все остальные настройки (например, уровень оптимизации).
Объединяя разные параметры, можно уточнять настройки с очень высоким уровнем детализации. Допустим, я хочу знать обо всех проблемах, относящихся к производительности, на данный момент не желаю отвлекаться на серверные проблемы, а предупреждение PLW-05005
(выход из функции без RETURN
) должно рассматриваться как ошибка компиляции. Для этого вводится следующая команда:
ALTER SESSION SET PLSQL_WARNINGS=
'DISABLE:SEVERE'
,'ENABLE:PERFORMANCE'
,'ERROR:05005';
Особенно полезна возможность интерпретации предупреждений как ошибок. Возьмем предупреждение PLW-05005; если оставить его без внимания при компиляции функции no_return (см. ниже), программа откомпилируется, и я смогу использовать ее в приложении:
SQL> CREATE OR REPLACE FUNCTION no_return
2 RETURN VARCHAR2
3 AS
4 BEGIN
5 DBMS_OUTPUT.PUT_LINE (
6 'Here I am, here I stay');
7 END no_return;
8 /
SP2-0806: Function created with compilation warnings
SQL> SHOW ERR
Errors for FUNCTION NO_RETURN:
LINE/COL ERROR
-------------------------------------------------------
1/1 PLW-05005: function NO_RETURN returns without value at line 7
Если теперь изменить интерпретацию ошибки приведенной выше командой ALTER SESSION
и перекомпилировать no_return
, компилятор немедленно остановит попытку:
Warning: Procedure altered with compilation errors
Кстати говоря, настройки также можно изменить только для конкретной программы и пометить предупреждение как ошибку командой следующего вида:
ALTER PROCEDURE no_return COMPILE PLSQL_WARNINGS = 'error:6002' REUSE SETTINGS
/
Во всех этих разновидностях команды ALTER
ключевое слово ALL
может использоваться как простое и удобное обозначение всех категорий предупреждений:
ALTER SESSION SET PLSQL_WARNINGS='ENABLE:ALL';
Oracle также предоставляет пакет DBMS_WARNING
со сходными возможностями по установке и изменению параметров компиляции через PL/SQL API
. В отличие от команды ALTER, DBMS_WARNING
позволяет вносить изменения в конфигурацию тех предупреждений, которые вас интересуют, оставляя другие без изменений. Также после завершения работы можно легко восстановить исходные настройки.
Пакет DBMS_WARNING
проектировался для использования в установочных сценариях, в которых может возникнуть необходимость отключения некоторых предупреждений или интерпретации предупреждения как ошибки для отдельных компилируемых программ. Может оказаться, что некоторые сценарии (внешние по отношению к тем, за которые вы отвечаете) вам неподконтрольны. Автор каждого сценария должен иметь возможность задать нужную конфигурацию предупреждений, наследуя более широкий спектр настроек из глобальной области действия.
Некоторые полезные предупреждения PL/SQL
В следующих разделах я представлю небольшую подборку предупреждений, реализованных Oracle
, — с примерами кода, для которого они выдаются, и описаниями особенно интересного поведения.
Чтобы просмотреть полный список предупреждений для любой конкретной версии Oracle
, найдите раздел PLW
в книге «Error Messages» документации Oracle.
PLW-05000: несовпадение в NOCOPY между спецификацией и телом
Рекомендация NOCOPY
сообщает базе данных Oracle, что вы, если это возможно, предпочли бы не создавать копии аргументов IN OUT
. Отказ от копирования может повысить производительность программ, передающих большие структуры данных — например, коллекции или CLOB
.
Рекомендация NOCOPY
должна быть включена как в спецификацию, так и в тело программы (актуально для пакетов и объектных типов). Если рекомендация не присутствует в обоих местах, база данных применяет настройку, указанную в спецификации.
Пример кода, генерирующего это предупреждение:
PACKAGE plw5000
IS
TYPE collection_t IS
TABLE OF VARCHAR2 (100);
PROCEDURE proc (
collection_in IN OUT NOCOPY
collection_t);
END plw5000;
PACKAGE BODY plw5000
IS
PROCEDURE proc (
collection_in IN OUT
collection_t)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE ('Hello!');
END proc;
END plw5000;
Предупреждения компилятора отображаются в следующем виде:
SQL> SHOW ERRORS PACKAGE BODY plw5000
Errors for PACKAGE BODY PLW5000:
LINE/COL ERROR
-------- ---------------------------------------------------------------
3/20 PLW-05000: mismatch in NOCOPY qualification between specification
and body
3/20 PLW-07203: parameter 'COLLECTION_IN' may benefit from use of the
NOCOPY compiler hint
PLW-05001: предыдущее использование строки противоречит этому использованию
Предупреждение проявляется при объявлении нескольких переменных или констант с одинаковыми именами. Оно также может проявиться в том случае, если список параметров программы, определенный в спецификации пакета, отличается от списка в определении из тела пакета.
Возможно, вы скажете: «Да, я видел эту ошибку, но это именно ошибка компиляции, а не предупреждение». Собственно, вы правы — следующая программа не откомпилируется:
PROCEDURE plw5001
IS
a BOOLEAN;
a PLS_INTEGER;
BEGIN
a := 1;
DBMS_OUTPUT.put_line ('Will not compile');
END plw5001;
Компилятор выдает ошибку PLS-00371
(в разделе объявлений разрешено не более одного объявления ‘A’).
Почему же для этой ситуации создано предупреждение? Попробуем удалить присваивание переменной с именем a:
SQL> CREATE OR REPLACE PROCEDURE plw5001
2 IS
3 a BOOLEAN;
4 a PLS_INTEGER;
5 BEGIN
6 DBMS_OUTPUT.put_line ('Will not compile?');
7 END plw5001;
8 /
Procedure created.
Программа откомпилируется! База данных не выдает ошибку PLS-00371
, потому что я не использую ни одну из переменных в своем коде. Предупреждение PLW
-05001 устраняет этот недостаток, сообщая о том, что я объявляю одноименные переменные без использования:
SQL> ALTER PROCEDURE plw5001 COMPILE plsql_warnings = 'enable:all';
SP2-0805: Procedure altered with compilation warnings
SQL> SHOW ERRORS
Errors for PROCEDURE PLW5001:
LINE/COL ERROR
--------------------------------------------------------------------------
4/4 PLW-05001: previous use of 'A' (at line 3) conflicts with this use
PLW-05003: фактический параметр с IN и NOCOPY может иметь побочные эффекты
Используя NOCOPY
с параметром IN OUT
, вы приказываете PL/SQL
передавать аргумент по ссылке, а не по значению. Это означает, что любые изменения в аргументе вносятся непосредственно в переменную во внешней области действия. С другой стороны, при передаче «по значению» (ключевое слово NOCOPY
отсутствует, или компилятор игнорирует рекомендацию NOCOPY
) изменения вносятся в локальную копию параметра IN OUT
. Когда программа завершается, изменения копируются в фактический параметр. (Если произойдет ошибка, измененные значения не копируются в фактический параметр.) Рекомендация NOCOPY
повышает вероятность совмещения имен аргументов, то есть ссылки на один блок памяти по двум разным именам.
Совмещение имен усложняет понимание и отладку кода; предупреждение компилятора, выявляющее эту ситуацию, будет чрезвычайно полезным.
Возьмем следующую программу:
PROCEDURE very_confusing (
arg1 IN VARCHAR2
, arg2 IN OUT VARCHAR2
, arg3 IN OUT NOCOPY VARCHAR2
) продолжение #
IS
BEGIN
arg2 := 'Second value';
DBMS_OUTPUT.put_line ('arg2 assigned, arg1 = ' || arg1);
arg3 := 'Third value';
DBMS_OUTPUT.put_line ('arg3 assigned, argl = ' || argl);
END;
Программа достаточно проста: передаются три строки, две из которых объявлены как IN OUT
; аргументам IN OUT
присваиваются значения; после каждого присваивания выводится значение первого аргумента IN
. Теперь я запускаю процедуру и передаю одну локальную переменную во всех трех параметрах:
SQL> DECLARE
2 str VARCHAR2 (100) := 'First value';
3 BEGIN
4 DBMS_OUTPUT.put_line ('str before = ' || str);
5 ery_confusing (str, str, str);
6 DBMS_OUTPUT.put_line ('str after = ' || str);
7 END;
8 /
str before = First value
arg2 assigned, arg1 = First value
arg3 assigned, arg1 = Third value
str after = Second value
Хотя процедура very_confusing
продолжает выполняться, присваивание arg2 не отражается на значении аргумента arg1
. Однако когда значение присваивается arg3
, значение arg1
(аргумент IN) заменяется на «Third value
»! Более того, при завершении very_confusing присваивание arg2
было применено к переменной str
. Таким образом, при возврате управления во внешний блок переменной str
присваивается значение «Second value
», фактически заменяющее результат присваивания «Third value
».
Как говорилось ранее, совмещение имен параметров может порождать очень запутанные ситуации. Если включить предупреждения компилятора, в таких программах, как plw5003, могут быть выявлены потенциальные проблемы совмещения имен:
SQL> CREATE OR REPLACE PROCEDURE plw5003
2 IS
3 str VARCHAR2 (100) := 'First value';
4 BEGIN
5 DBMS_OUTPUT.put_line ('str before = ' || str);
6 very_confusing (str, str, str);
7 DBMS_OUTPUT.put_line ('str after = ' || str);
8 END plw5003;
9 /
SP2-0804: Procedure created with compilation warnings
SQL> SHOW ERR
Errors for PROCEDURE PLW5003:
LINE/COL ERROR
-------- -----------------------------------------------------------------
6/4 PLW-05003: same actual parameter(STR and STR) at IN and NOCOPY
may have side effects
6/4 PLW-05003: same actual parameter(STR and STR) at IN and NOCOPY
may have side effects
PLW-05004: идентификатор также объявлен в пакете STANDARD или является встроенным в SQL
Многие разработчики PL/SQL не знают о пакете STANDARD
и его влиянии на код PL/ SQL
. Например, многие программисты считают, что такие имена, как INTEGER
и TO_CHAR
, являются зарезервированными словами языка PL/SQL
. Однако на самом деле это тип данных и функция, объявленные в пакете STANDARD
.
standard
— один из двух пакетов по умолчанию в PL/SQL
(другой — DBMS_STANDARD
). Поскольку STANDARD
является пакетом по умолчанию, вам не нужно уточнять ссылки на такие типы данных, как INTEGER, NUMBER, PLS_INTEGER
и т. д., именем STANDARD
— хотя при желании это можно сделать.
Предупреждение PLW-5004
сообщает об объявлении идентификатора с таким же именем, как у элемента STANDARD
(или встроенным именем SQL; многие встроенные имена, хотя и не все, объявляются в STANDARD
).
Рассмотрим эту процедуру:
1 PROCEDURE plw5004
2 IS
3 INTEGER NUMBER;
4
4 PROCEDURE TO_CHAR
5 IS
6 BEGIN
7 INTEGER := 10;
8 END TO_CHAR;
9 BEGIN
10 TO_CHAR;
11 END plw5004;
Для этой процедуры компилятор выводит следующие предупреждения:
LINE/COL ERROR
-------- ------------------------------------------------------------
3/4 PLW-05004: identifier INTEGER is also declared in STANDARD
or is a SQL builtin
5/14 PLW-05004: identifier TO_CHAR is also declared in STANDARD
or is a SQL builtin
Старайтесь избегать использования имен элементов, определенных в пакете STANDARD
, если только у вас нет для этого очень веских причин.
PLW-05005: функция возвращает управление без значения
Очень полезное предупреждение — функция, не возвращающая значение, явно очень плохо спроектирована. Это одно из предупреждений, которые я бы рекомендовал интерпретировать как ошибку (синтаксис «ERROR:5005
») в настройках PLSQL_WARNINGS
. Мы уже рассматривали один пример такой функции: no_return. Тот код был тривиальным; во всем исполняемом разделе не было ни одной команды RETURN
. Конечно, код может быть и более сложным. Тот факт, что команда RETURN
не выполняется, может быть скрыт за завесой сложной условной логики.
Впрочем, по крайней мере иногда в подобных ситуациях база данных способна обнаружить проблему, как в следующей программе:
1 FUNCTION no_return (
2 check_in IN BOOLEAN)
3 RETURN VARCHAR2
4 AS
5 BEGIN
6 IF check_in
7 THEN
8 RETURN 'abc';
9 ELSE
10 DBMS_OUTPUT.put_line (
11 'Here I am, here I stay');
12 END IF;
13 END no_return;
База данных обнаружила логическую ветвь, не приводящую к выполнению RETURN
, поэтому для программы выдается предупреждение. Файл plw5005.sql
на сайте github содержит более сложную условную логику, которая демонстрирует, что предупреждение выдается и в более сложных программных структурах.
PLW-06002: недостижимый код
База данных Oracle теперь умеет проводить статический анализ программы для выявления строк кода, которые ни при каких условиях не получат управление во время выполнения. Это исключительно ценная информация, но иногда компилятор предупреждает о наличии проблемы в строках, которые на первый взгляд недостижимыми вовсе не являются. Более того, в описании действий, предпринимаемых для этой ошибки, говорится, что «предупреждение следует отключить, если большой объем кода был сделан недостижимым намеренно, а предупреждение приносит больше раздражения, чем пользы».
Пример такого предупреждения приводился ранее в разделе «Пример». Теперь рассмотрим следующий код:
1 PROCEDURE plw6002
2 AS
3 l_checking BOOLEAN := FALSE;
4 BEGIN
5 IF l_checking
6 THEN
7 DBMS_OUTPUT.put_line ('Never here...');
8 ELSE
9 DBMS_OUTPUT.put_line ('Always here...');
10 GOTO end_of_function;
11 END IF;
12 <<end_of_function>>
13 NULL;
14 END plw6002;
В Oracle Database 10g и выше для этой программы выдаются следующие предупреждения:
LINE/COL ERROR
--------- ---------------------------------
5/7 PLW-06002: Unreachable code
7/7 PLW-06002: Unreachable code
13/4 PLW-06002: Unreachable code
Понятно, почему строка 7 помечена как недостижимая: l_checking
присваивается значение FALSE
, поэтому строка 7 выполняться не будет. Но почему строка 5 помечена как недостижимая? На первый взгляд этот код будет выполняться всегда! Более того, строка 13 тоже должна выполняться всегда, потому что GOTO
передает управление этой строке по метке. И все же эта строка тоже помечена как недостижимая.
Такое поведение объясняется тем, что до выхода Oracle Database 11g предупреждение о недостижимости кода генерируется после его оптимизации. В Oracle Database 11g и выше анализ недостижимого кода стал намного более понятным и полезным.
Компилятор не вводит вас в заблуждение; говоря, что строка N недостижима, он сообщает, что она никогда не будет выполняться в соответствии со структурой оптимизированного кода.
Некоторые ситуации с недостижимым кодом не обнаруживаются компилятором. Пример:
FUNCTION plw6002 RETURN VARCHAR2
AS
BEGIN
RETURN NULL;
DBMS_OUTPUT.put_line ('Never here...');
END plw6002;
Разумеется, вызов DBMS_OUTPUT.PUT_LINE
недостижим, но в настоящее время компилятор не обнаруживает это обстоятельство — до версии 12.1.
PLW-07203: рекомендация NOCOPY может принести пользу в объявлении параметра
Как упоминалось ранее в отношении PLW-05005
, использование NOCOPY
для сложных, больших параметров IN OUT
может улучшить производительность программ в некоторых условиях. Это предупреждение выдается для программ, у которых включение NOCOPY
для параметров IN OUT
может повысить эффективность выполнения. Пример такой программы:
PACKAGE plw7203
IS
TYPE collection_t IS TABLE OF VARCHAR2 (100);
PROCEDURE proc (collection_in IN OUT collection_t);
END plw7203;
Это еще одно предупреждение, которое будет генерироваться во многих программах и вскоре начнет раздражать. Безусловно, предупреждение вполне справедливо, но в большинстве случаев последствия такой оптимизации останутся незамеченными. Более того, вряд ли вам удастся переключиться на NOCOPY
без внесения изменений для обработки ситуаций с аварийным завершением программы, при котором данные остаются в неопределенном состоянии.
PLW-07204: преобразование типа столбца может привести к построению неоптимального плана запроса
Предупреждение выдается при вызове команд SQL из PL/SQL, при котором происходят неявные преобразования. Пример:
FUNCTION plw7204
RETURN PLS_INTEGER
AS
l_count PLS_INTEGER;
BEGIN
SELECT COUNT(*) INTO l_count
FROM employees
WHERE salary = '10000';
RETURN l_count;
END plw7204;
С этим предупреждением тесно связано предупреждение PLW-7202
(тип передаваемого параметра приводит к преобразованию типа столбца).
PLW-06009: обработчик OTHERS не завершается вызовом RAISE или RAISE_APPLICATION_ERROR
Это предупреждение (добавленное в Oracle Database 11g) выводится тогда, когда в обработчике исключений OTHERS
не выполняется та или иная форма RAISE
(повторное инициирование того же исключения или инициирование другого исключения), и не вызывается RAISE_APPLICATI0N_ERR0R
. Другими словами, существует большая вероятность того, что программа «поглощает» исключение и игнорирует его. Ситуации, в которых ошибки действительно должны игнорироваться, встречаются довольно редко. Чаще исключение должно передаваться во внешний блок:
FUNCTION plw6009
RETURN PLS_INTEGER
AS
l_count PLS_INTEGER;
BEGIN
SELECT COUNT ( * ) INTO l_count
FROM dual WHERE 1 = 2;
RETURN l_count;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('Error!');
RETURN 0;
END plw6009;
Вас заинтересует / Intresting for you:
PLS-00103: Encountered the symbol “CREATE” error occurs while running a CREATE block using script, you have not used / (front slash) to let SQLPlus know when the block completes, as a PL/SQL block may contain many instances of ; (semicolon). The CREATE block in the script should be terminated with a front slash (/) to inform Oracle that the code block has been completed.
The error occurs if you try to create two or more PL/SQL objects (procedure, function, package, type, etc.) at the same time. In a single sql session, the PL/SQL objects cannot be created together. You attempt to create several PL/SQL objects at the same time. The error PLS-00103: Encountered the symbol “CREATE” occurs in oracle
The PL/SQL objects such as procedure, functions, package, type etc are container objects that can be used in another objects. A procedure might be called from another procedure. A function can be used within a process. If you try to create two PL/SQL container objects, you’ll get an error PLS-00103: Encountered the symbol “CREATE”.
The two or more ddl, dml, dcl commands can execute in a single session. If two or more PL/SQL objects can not be created in a single command. The oracle sql commands are independent that can not be used in another sql command. The PL/SQL commands can be stored in local variable and can be used for the manipulation.
The Problem
The PL/SQL objects can be used in another PL/SQL objects. For example, the function can be called within the procedure. A procedure can be used within the function. If you try to create PL/SQL objects together, all the object are stored in buffer that can be rolled back. Oracle will not allow to create a PL/SQL object that refers to an another object in the buffer. Oracle forces the object to be persisted.
create type type_student;
create type type_course;
Error
Type TYPE_STUDENT compiled
LINE/COL ERROR
--------- -------------------------------------------------------------
2/1 PLS-00103: Encountered the symbol "CREATE"
Errors: check compiler log
Solution 1
When creating two or more PL/SQL objects, such as a procedure, function, package, or type, the PL/SQL objects should be terminated with a “/.” If Oracle detects a “/” terminator in the PL/SQL code, the objects in the oracle buffer are persisted in the database before going to the next code. Each PL/SQL object will be executed in a separate Oracle buffer, one after the other. PL/SQL objects are saved as soon as they are created.
The ; terminates a SQL query, whereas the / executes whatever is currently in the “buffer.” As a result, when you use a ; and a /, the statement is executed twice.
create type type_student;
/
create type type_course;
Output
Type TYPE_STUDENT compiled
Type TYPE_COURSE compiled
Solution 2
If you try to create a few PL/SQL objects in the PL/SQL code, the PL/SQL objects can be created separately. By executing each PL/SQL object individually, the objects may be created one at a time. Run each command in sequence, ensuring that the objects are created before executing the next PL/SQL code.
Code
create type type_student;
Output
Type TYPE_STUDENT compiled
Code
create type type_course;
Output
Type TYPE_COURSE compiled
A blog post about Oracle error codes? Curiosities about them, even?
If you doubt that this might be possible or of interest, then answer these two questions:
Can an error in Oracle have more than one error code?
Are error codes positive or negative?
If you answered «yes» for the first and «yes and no» for the second, you probably don’t need to read this post.
Oracle Errors With More Than One Error Code?
Well that wouldn’t be very normalized, would it?
But it is true that there at least one error that has two different error codes associated with it, and it’s one of the most common «errors» you’ll encounter in your code:
The NO_DATA_FOUND exception
When I execute a SELECT-INTO statement, Oracle will raise NO_DATA_FOUND if no row is found for the query. It will raise TOO_MANY_ROWS if more than one row is found.
So what error code is associated with NO_DATA_FOUND?
The following code demonstrates this curiosity. I create a table with no data. My SELECT-INTO, therefore, finds no rows and the error message displayed (there was no exception handler) shows that the error code is -1403 (or is it 1403? I explore that curiosity later).
CREATE TABLE t (n NUMBER)
/
DECLARE
l_n NUMBER;
BEGIN
SELECT n INTO l_n FROM t;
END;
/
ORA-01403: no data found
Now I will handle the exception, first with WHEN OTHERS then with WHEN NO_DATA_FOUND, and display the value returned by SQLCODE.
DECLARE
l_n NUMBER;
BEGIN
SELECT n INTO l_n FROM t;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('Error code = ' || SQLCODE);
END;
/
Error code = 100
DECLARE
l_n NUMBER;
BEGIN
SELECT n INTO l_n FROM t;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line ('Error code = ' || SQLCODE);
END;
/
Error code = 100
100, not -1403!
That’s certainly very odd. How can this be? Well, you what they say: go to the source for the best answer, and the source in this case is the code of the STANDARD package, which defines many datatypes and exceptions in the PL/SQL language. In STANDARD, you will find the following:
NO_DATA_FOUND exception;
pragma EXCEPTION_INIT(NO_DATA_FOUND, 100);
....
TOO_MANY_ROWS exception;
pragma EXCEPTION_INIT(TOO_MANY_ROWS, '-1422');
That pragma is used to associate an error code with a named exception (explore this pragma on LiveSQL here). We can do that in our code as well (which I show you below, thereby introducing another oddity for NO_DATA_FOUND). In this case, the STANDARD package pre-defines a number of named exceptions that are commonly used. And as you can see, the association is made to 100 and not -1403.
I must confess I have not tracked down any official documentation on this, but it is pretty clear that 100 is the ANSI-standard error code for «no rows found». In fact, Intersystems elaborates a bit further as follow:
SQLCODE=100 indicates that the SQL operation was successful, but found no data to act upon. This can occur for a number of reasons. For a SELECT these include: the specified table contains no data; the table contains no data that satisfies the query criteria; or row retrieval has reached the final row of the table. For an UPDATE or DELETE these include: the specified table contains no data; or the table contains no row of data that satisfies the WHERE clause criteria. In these cases %ROWCOUNT=0.
Notice that it states that 100 indicates the «SQL operation was successful.» I like this because it helps explain why the error code is not, say, -100. It also reinforces the point that just because a query does not return any rows does not mean that there is an error. It’s just a data condition.
More NO_DATA_FOUND Oddities
Remember I said you could use the EXCEPTION_INIT pragma to associate a code with your own named exception? Here’s an example:
DECLARE
e_bad_date_format EXCEPTION;
PRAGMA EXCEPTION_INIT (e_bad_date_format, -1830);
BEGIN
DBMS_OUTPUT.put_line (TO_DATE ('2010 10 10 44:55:66', 'YYYSS'));
EXCEPTION
WHEN e_bad_date_format
THEN
DBMS_OUTPUT.put_line ('Bad date format');
END;
I can even use this pragma to assign an error code already assigned a pre-defined exception name, like TOO_MANY_ROWS:
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, -1422);
BEGIN
RAISE my_exception;
END;
/
ORA-01422: exact fetch returns more than requested number of rows
And what about -1403? A big, fat no way!
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, -1403);
BEGIN
RAISE my_exception;
END;
/
PLS-00701: illegal ORACLE error number -1403 for PRAGMA EXCEPTION_INIT
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, -1403);
BEGIN
RAISE my_exception;
END;
/
PLS-00701: illegal ORACLE error number -1403 for PRAGMA EXCEPTION_INIT
But 100 works just fine.
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, 100);
BEGIN
RAISE my_exception;
END;
/
ORA-01403: no data found
Notice also that the inability to use EXCEPTION_INIT with -1403 manifests as a compile-time error («PLS») not a runtime Oracle error («ORA»).
Error Codes Negative or Positive?
I bet that most of you believe that error codes are (mostly) negative. That view would certainly be reinforced with code like this:
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, -1422);
BEGIN
RAISE my_exception;
EXCEPTION
WHEN OTHERS
THEN
IF SQLCODE = -1422
THEN
DBMS_OUTPUT.PUT_LINE ('Negative!');
END IF;
END;
/
Negative!
Sure looks negative to me. And if I try to use that pragma with a positive number that is not 100 or 1 (the error code associated with a user-defined exception that has not been essociated with an error code by EXCEPTION_INIT), I get an error:
DECLARE
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT (my_exception, 1422);
BEGIN
RAISE my_exception;
END;
/
PLS-00701: illegal ORACLE error number 1422 for PRAGMA EXCEPTION_INIT
So, it’s OK, so error codes are generally negative. Everyone agreed on that? Well, maybe everyone but a few people who work(ed) at Oracle and maybe everything but a few features in Oracle Database.
It turns out that sometimes error codes are stored without that pesky «-«. Which is understandable, because there are clearly two ways to interpret the hyphen in this text:
ORA-01422
1. A negative sign
2. A hyphen
Let’s first consider the SQLERRM function. Most people use it to obtain the error message of the current error (though you would be better off using DBMS_UTILITY.FORMAT_ERROR_STACK or the UTL_CALL_STACK API).
Relatively few developers know that you can also pass an error code to SQLERRM and it will return the generic message associated with that code. Here’s an example:
BEGIN
DBMS_OUTPUT.put_line (SQLERRM (-1422));
END;
ORA-01422: exact fetch returns more than requested number of rows
That’s nice. But what if I leave off the «-«?
BEGIN
DBMS_OUTPUT.put_line (SQLERRM (1422));
END;
-1422: non-ORACLE exception
Gee, that’s telling it like it is.
But why didn’t SQLERRM talk to SQL%BULK_EXCEPTIONS and get their story straight?
SQL%BULK_EXCEPTIONS is a pseudo-collection or records that is populated with any errors in the execution of FORALL statements. Check out my LiveSQL tutorial on bulk processing for lots more details.
Each record contains the index into the collection for each statement that failed along with the error code of the failure. Guess what? The error code is recorded without what that person clearly thought was a hyphen.
Notice in the code below (an excerpt from my LiveSQL script on SAVE EXCEPTIONS) I must multiply the error code value by -1 so that I can retrieve the error message.
EXCEPTION
WHEN std_errs.failure_in_forall
THEN
FOR indx IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
LOOP
DBMS_OUTPUT.put_line (
'Oracle error is '
|| SQLERRM ( -1 * SQL%BULK_EXCEPTIONS (indx).ERROR_CODE));
END LOOP;
ROLLBACK;
END;
No big deal, once you aware of it. But….kind of odd, eh?
Well, there is some consistency in our inconsistency. If you use the LOG ERRORS feature for non-query DML (which allows you to suppress errors at the row level), then Oracle will automatically record the error code, message and more in an error logging table. And in this table, error codes are stored as unsigned integers, as you can see below in the output from this LiveSQL script on LOG ERRORS:
So those are my little discoveries on the nuances of error codes in Oracle Database.
Do you have your own story about Oracle error codes you’d like to share?
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