Sub topic 12
Capturing the error stack and backtrace
When a PL/SQL program fails in production, the message alone rarely tells you where. This chapter covers the tools that record what failed and where it failed: DBMS_UTILITY.FORMAT_ERROR_STACK, DBMS_UTILITY.FORMAT_ERROR_BACKTRACE, DBMS_UTILITY.FORMAT_CALL_STACK, and the structured UTL_CALL_STACK package.
It assumes you can write an EXCEPTION section with WHEN OTHERS, read SQLCODE and SQLERRM, and use RAISE and RAISE_APPLICATION_ERROR. Examples use DBMS_OUTPUT, so run SET SERVEROUTPUT ON first.
Three different questions
An error report can answer three separate questions. Each has its own function.
| Question | Tool | Notes |
|---|---|---|
| What went wrong? | `DBMS_UTILITY.FORMAT_ERROR_STACK` | All error messages in the current error, up to 2000 bytes. |
| Where was the error raised? | `DBMS_UTILITY.FORMAT_ERROR_BACKTRACE` | One `ORA-06512` line per subprogram on the path from the raise point to the handler. |
| How did execution get here? | `DBMS_UTILITY.FORMAT_CALL_STACK` | The current chain of calls. It does not need an error. |
SQLERRM returns only the top message, truncated to 512 bytes. It also tells you nothing about location. In a handler, prefer FORMAT_ERROR_STACK for the message and FORMAT_ERROR_BACKTRACE for the location.
Reading a backtrace
The backtrace is the most useful of the three. Create two procedures that call each other, with a failure at the bottom:
CREATE OR REPLACE PROCEDURE inner_proc IS
l_val NUMBER;
BEGIN
l_val := 1 / 0;
END inner_proc;
/
CREATE OR REPLACE PROCEDURE outer_proc IS
BEGIN
inner_proc;
END outer_proc;
/Now call outer_proc from a block that prints both values:
BEGIN
outer_proc;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('--- stack ---');
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_STACK);
DBMS_OUTPUT.PUT_LINE('--- backtrace ---');
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
END;
/The output looks like this. Your schema name will differ.
--- stack ---
ORA-01476: divisor is equal to zero
--- backtrace ---
ORA-06512: at "HR.INNER_PROC", line 4
ORA-06512: at "HR.OUTER_PROC", line 3
ORA-06512: at line 2Read the backtrace from the top. The first line is the statement that raised the error: line 4 of HR.INNER_PROC. Each following line is a caller, ending at the anonymous block that holds the handler. Anonymous blocks have no name, so their line has no unit.
Replace the empty fence above with the diagram below. It shows the same path.
Why the backtrace survives a re-raise
A bare RAISE inside a handler re-raises the current exception without changing where it started. An intermediate layer can therefore log and re-raise, and the backtrace still points at the original line:
CREATE OR REPLACE PROCEDURE middle_proc IS
BEGIN
inner_proc;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('middle_proc saw: ' || SQLERRM);
RAISE;
END middle_proc;
/If a caller prints the backtrace after middle_proc fails, the first line is still "HR.INNER_PROC", line 4. The line of the RAISE is not substituted.
What resets the backtrace
Raising a new error starts a new backtrace. This applies to RAISE_APPLICATION_ERROR and to RAISE some_exception with an exception name. The original location is gone unless you saved it first.
CREATE OR REPLACE PROCEDURE run_nightly IS
BEGIN
outer_proc;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Original backtrace:');
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE_APPLICATION_ERROR(-20010, 'Nightly job failed', TRUE);
END run_nightly;
/The third argument, TRUE, is keep_errors. It adds the new error to the existing stack instead of replacing it. A caller that prints FORMAT_ERROR_STACK sees both ORA-20010 and ORA-01476. The backtrace, however, now starts at line 8 of RUN_NIGHTLY, the RAISE_APPLICATION_ERROR call. That is why the handler prints the original backtrace before raising.
Capturing into variables
A reusable pattern is to read all three values once and then use the copies:
DECLARE
l_stack VARCHAR2(4000);
l_backtrace VARCHAR2(4000);
BEGIN
outer_proc;
EXCEPTION
WHEN OTHERS THEN
l_stack := DBMS_UTILITY.FORMAT_ERROR_STACK;
l_backtrace := DBMS_UTILITY.FORMAT_ERROR_BACKTRACE;
DBMS_OUTPUT.PUT_LINE(l_stack || l_backtrace);
RAISE;
END;
/Both functions return VARCHAR2. Size your variable or log column for the combined text, because a deep call chain produces many lines.
FORMAT_CALL_STACK is not an error tool
DBMS_UTILITY.FORMAT_CALL_STACK reports where execution is now, not where an error happened. Call it inside a handler and you get the call chain of the handler. That is rarely the same as the raise point. Use it for tracing normal execution, for example to record who called a utility routine. Use the backtrace for failures.
Structured access with UTL_CALL_STACK
The DBMS_UTILITY functions return text that you must parse if you want individual parts. From Oracle Database 12c, the UTL_CALL_STACK package returns each part separately:
BEGIN
outer_proc;
EXCEPTION
WHEN OTHERS THEN
FOR i IN 1 .. UTL_CALL_STACK.ERROR_DEPTH LOOP
DBMS_OUTPUT.PUT_LINE(
'Error ' || i || ': ORA-' ||
LPAD(UTL_CALL_STACK.ERROR_NUMBER(i), 5, '0') ||
' ' || UTL_CALL_STACK.ERROR_MSG(i));
END LOOP;
FOR i IN 1 .. UTL_CALL_STACK.BACKTRACE_DEPTH LOOP
DBMS_OUTPUT.PUT_LINE(
'Frame ' || i || ': ' ||
NVL(UTL_CALL_STACK.BACKTRACE_UNIT(i), '(anonymous)') ||
' line ' || UTL_CALL_STACK.BACKTRACE_LINE(i));
END LOOP;
END;
/ERROR_DEPTH counts the errors in the stack. BACKTRACE_DEPTH counts the backtrace frames. Index 1 is the most recent entry in each list, so frame 1 here is INNER_PROC line 4. This form suits code that writes each frame to its own column or table row, with no string parsing.
Edge cases and pitfalls
- Outside a handler. If no exception is active,
FORMAT_ERROR_BACKTRACEreturnsNULL. Do not rely on it after the handler has finished. - Truncation.
FORMAT_ERROR_STACKreturns at most 2000 bytes. Assigning it to aVARCHAR2(100)variable raisesORA-06502, a new error inside your handler. - Line numbers belong to the stored source. In a stored unit, line 1 is the line that starts with
PROCEDURE,FUNCTION, orPACKAGE. It is not theCREATE OR REPLACEkeyword, so a script editor may show numbers offset from the database's. UseSELECT line, text FROM user_source WHERE name = 'INNER_PROC'to confirm a line. - Recompilation. The backtrace reports the version of the code that ran. If you edit a procedure after the failure, the reported lines no longer match the source.
- Handling hides the trail. If a handler catches an error and does not re-raise, the caller never sees it. Capture the stack and backtrace in that handler, or the information is lost.
- A swallowed
WHEN OTHERS. A handler that only printsSQLERRMand returns normally gives the caller no sign of failure and no location. Add the backtrace, then log, then re-raise.
Putting it together
In a layered application, apply this rule: capture where you handle, and add context only when you wrap.
- In the outermost handler, the one that decides to stop, record
FORMAT_ERROR_STACKandFORMAT_ERROR_BACKTRACE. - In inner layers, re-raise with a bare
RAISEso the original location is kept. - If an inner layer must translate an error into an application error, record the backtrace before raising the new one, and pass
TRUEforkeep_errors.
The next chapters on transaction control and autonomous logging build on this. They show how to store the captured text so it survives a rollback.
Exercise
A procedure load_data fails with ORA-01476 at line 12. Its handler does RAISE_APPLICATION_ERROR(-20050, 'Load failed'); without capturing anything first. The caller prints DBMS_UTILITY.FORMAT_ERROR_BACKTRACE. Does the caller see line 12? What two changes to the handler would keep both the original message and the original location?
Show answer
No. Raising a new error with RAISEAPPLICATIONERROR starts a new backtrace, so the caller sees the line of the RAISEAPPLICATIONERROR call in loaddata, not line 12. Before raising, save DBMSUTILITY.FORMATERRORBACKTRACE (and print or log it), and pass TRUE as the third argument (keep_errors) so ORA-01476 stays in the error stack beside ORA-20050.
Exercise
Why is a VARCHAR2(200) variable a poor choice for holding DBMS_UTILITY.FORMAT_ERROR_STACK, and what happens if the text is longer?
Show answer
The function can return up to 2000 bytes. Assigning a longer value to a smaller variable raises ORA-06502 (character string buffer too small) inside the handler, which replaces the error you were trying to record. Declare the variable as VARCHAR2(4000), or at least 2000.