Extracting a stack trace from a Java Exception in Oracle Forms
I recently came across a situation where I needed to see the stack trace in Forms since I had received a Java Exception in a PLSQL Exception section. It turned out it isn't as easy as calling getStackTrace on the java.lang.Exception and loop through the resulting Java array and do toString on each. Here is what you have to do:
First you need to import these classes:
java.lang.StackTraceElement
java.lang.Exception
To do that, you type in the full class name in the Java Importer dialog.

Then you click the Import button and a PLSQL will be created to make it possible to call out to the two classes.
Then you write this code in the PLSQL Exception handler:
declare
excep ora_java.jobject;
stack_trace ora_java.jarray;
stackTrcElement ora_java.jobject;
begin
...
exception
when ora_java.java_error then
message('Error: '||ora_java.last_error);
return 0;
when ora_java.exception_thrown then
excep:=ora_java.last_exception;
:control_blk.excp:='Exception: '||Exception_.toString(excep);
--Get an array of StackTraceElement from the Exception
stack_trace:=Exception_.getStackTrace(excep);
--Loop over all the Elements
for i in 0..ora_java.get_array_length(stack_trace) loop
--Get each Element
stackTrcElement:=ora_java.get_object_array_element(stack_trace, i);
--Make a string out of it and add it to the error field
:control_blk.excp:=:control_blk.excp||(10)||
stackTraceElement.toString(stackTrcElement);
end loop;
return 0;
end; The Exception_.getStackTrace(excep) returns an array of StackTraceElements. One of its methods is the toString that we need. In this example I iterate over the array and fill up a multi-line Forms field with the resulting strings. The result looks very much like the familiar stack traces you see in JDeveloper or any Java tool when Java throws an Exception. The field :control_blk.excp is a temporary field that I added to a control block in Forms to be able to see the stacktrace while I was debugging.
Comments:
raisedException := ORA_JAVA.LAST_EXCEPTION;
:exception_blk.excep := 'Exception: '||Exception_.toString(raisedException);
The message displayed is:
Invalid object type for argument 1.
If I use:
raisedException :=
EXCEPTION_.NEW( ora_java.last_exception)
Then the error is not raised.
However, I still don't get the stack trace. If I check the length of the jArray for the stack_trace, it's 0. The for loop than causes an error since it's going to iterate at least once.
Did I miss something? Did I have to do anything special when I did the Java Import for the java.lang.Exception or the java.lang.StackTraceElement classes?
I am able to get the stacktrace if I use a StringWriter/PrintWriter though.
Eric
Leave a comment: