Prints the Details of the Stack Frames of a Thread - Java Object Oriented Design

Java examples for Object Oriented Design:Exception

Description

Prints the Details of the Stack Frames of a Thread

Demo Code

public class Main {
  public static void main(String[] args) {
    m1();/*from   ww  w  .j a  v a  2s.c o  m*/
  }

  public static void m1() {
    m2();
  }

  public static void m2() {
    m3();
  }

  public static void m3() {
    Throwable t = new Throwable();
    StackTraceElement[] frames = t.getStackTrace();
    printStackDetails(frames);
  }

  public static void printStackDetails(StackTraceElement[] frames) {
    System.out.println("Frame count: " + frames.length);

    for (int i = 0; i < frames.length; i++) {
      // Get frame details
       int frameIndex = i; // i = 0 means top frame
      String fileName = frames[i].getFileName();
      String className = frames[i].getClassName();
      String methodName = frames[i].getMethodName();
      int lineNumber = frames[i].getLineNumber();

      // Print frame details
      System.out.println("Frame Index: " + frameIndex);
      System.out.println("File Name: " + fileName);
      System.out.println("Class Name: " + className);
      System.out.println("Method Name: " + methodName);
      System.out.println("Line Number: " + lineNumber);
    }
  }
}

Result


Related Tutorials