- Forward


Stack Tracing
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Getting Started
Back SMYC Forward
  • Calling Conventions:
    • A calling convention is a protocol governing the calling of and returning from "subprograms"
  • Some Observations:
    • A calling convention needs to consider information that needs to be saved/restored, parameters, return values, and the transfer of control
    • Many such protocols are possible
  • An Abstraction:
    • We can ignore the details and consider an abstract activation record (or invocation record or stack frame)
Using the Abstraction
Back SMYC Forward
  • StackTraceElement :
    • An encapsulation of a stack frame
  • Organization:
    • StackFrameElement objects are organized into a last-in, first-out (LIFO) "collection" (called a stack)
    • Each StackFrameElement object (except, perhaps, the top-most) represents a method invocation
    • The top-most StackFrameElement object can represent an execution point (e.g., the point at which a Throwable was created)
Where You Have Seen Them
Back SMYC Forward
  • Recall:
    • When an exception is never caught (e.g., re-thrown by every method including main()), the program terminates and a message is printed
  • The Contents of the Message:
    • The LIFO "collection" of StackFrameElement objects
Using Them Yourself
Back SMYC Forward
  • Obtaining a Stack Trace:
    • The static getStackTrace() method in the Throwable class will return the stack trace (i.e., the LIFO StackTraceElement[]) that was created when the Throwable was created
    • The getStackTrace() method belonging to a Thread object returns its current stack trace and the current Thread (loosely, the current sequence of instructions) can be obtained using the static currentThread() method in the Thread class
  • Useful Methods:
    • getClassName()
    • getFileName()
    • getLineNumber()
    • getMethodName()
An Example
Back SMYC Forward
javaexamples/oopbasics/banking/Account.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/oopbasics/banking/OverdraftAccount.java
 
An Example (cont.)
Back SMYC Forward
// Suppose we add the following to the amountAvailable() method // in OverdraftAccount StackTraceElement[] trace; trace = Thread.currentThread().getStackTrace(); for (int i=0; i<trace.length; i++) { System.out.println(trace[i]); } // And then do the following in the driver OverdraftAccount billSmith; billSmith = new OverdraftAccount(1001,15000.00,5000.00); billSmith.withdraw(19000.00);

The Stack Trace:

  OverdraftAccount.amountAvailable(OverdraftAccount.java:20)
  Account.withdraw(Account.java:59)
  Driver.main(Driver.java:36)
  

There's Always More to Learn
Back -