Java Glossary : trace

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : T words : trace.

trace
To analyse the flow of program logic, step by step is called tracing. Usually you would use a tool called a debugger to do this for you. One simple tool is Throwable.getStackTrace() which will tell you where you are in the code, and how you got there. The following technique lets you put the name of the current method in error messages, or the name of the caller of the currrent method, or its caller etc. You might use it something like this:

Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
for ( int i=0; i<es.length; i++ )
   {
   StackTraceElement e = es[i];
   System.out.println( " in class:" + e.getClassName()
                        + " in source file:" + e.getFileName()
                        + " in method:" + e.getMethodName()
                        + " at line:" + e.getLineNumber()
                        + " " + ( e.isNativeMethod() ? "native" : "" ) );
   }

imAt() in the following code sample will print out at com.mindprod.mypackage.Myclass.doSomething line 34. You could use similar code to return the name of the current class or method. Unfortunately, support for the methods this relies on is not guaranteed in all implementations.

/**
 * log where in the code you are, class/method/line
 */
static void imAt( PrintWriter log )
   {
   Throwable t = new Throwable();
   StackTraceElement[] es = t.getStackTrace();
   StackTraceElement e = es[1];
   log.println( "at " + e.getClassName()
                 + "."+ e.getMethodName()
                 + " line:" + e.getLineNumber() );
   }

In older Javas you will have to make do with new Throwable().printStackTrace(), or you can catch an exception and print with e.printStackTrace().


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 1345.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/trace.html J:\mindprod\jgloss\trace.html