75% developed

Stack trace

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Navigate Exceptions topic:v  d  e )


A Stack Trace is a list of method calls from the point when the application was started to the current location of execution within the program. A Stack Trace is produced automatically by the Java Virtual Machine when an exception is thrown to indicate the location and progression of the program up to the point of the exception. The most recent method calls are at the top of the list.

Computer code Code listing 6.3: StackTraceExample.java
public class StackTraceExample {
  public static void main(String[] args) {
    method1();
  }

  public static void method1() {
    method11();
  }

  public static void method11() {
    method111();
  }

  public static void method111() {
    throw new NullPointerException("Fictitious NullPointerException");
  }
}
Standard input or output Output for Code listing 6.3
Exception in thread "main" java.lang.NullPointerException: Fictitious NullPointerException
at StackTraceExample.method111(StackTraceExample.java:15)
at StackTraceExample.method11(StackTraceExample.java:11)
at StackTraceExample.method1(StackTraceExample.java:7)
at StackTraceExample.main(StackTraceExample.java:3)

The stack trace can be printed to the standard error by calling the public void printStackTrace() method of an exception.

From Java 1.4, the stack trace is encapsulated into an array of a java class called java.lang.StackTraceElement. The stack trace element array returned by Throwable.getStackTrace() method. Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created.

A stack frame represents the following information:

Example Code section 6.24: Stack frame.
public StackTraceElement(String declaringClass,
                         String methodName,
                         String fileName,
                         int lineNumber);

Creates a stack trace element representing the specified execution point.

Converting the stack trace into string[edit | edit source]

Many times for debugging purposes, we'd like to convert the stack trace to a String so we can log it to our log file.

The following code shows how to do that:

Example Code section 6.25: Save the stack trace.
import java.io.StringWriter;
import java.io.PrintWriter;

...

  Exception e = new NullPointerException();

  StringWriter outError = new StringWriter();
  e.printStackTrace(new PrintWriter(outError));
  String errorString = outError.toString();

  // Do whatever you want with the errorString


Clipboard

To do:
Add some exercises like the ones in Variables