javastack

How to understand how StackTraceElement works?


I'm very new to programming. I try to learn from Code Gym. But I still don't understand some things. For example, why is it crucial to put StackTraceElement[]... in last method on the chain in order for it to print all the methods that were used in that "chain". Why can't I start use this code in the main method like in second block of code. Sorry if it sounds stupid I just don't get it.

public class ExceptionPrzyklad
{
  public static void main(String[] args)
  {
    method1();
  }

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

  public static void method2()
  {
    method3();
  }

  public static void method3()
  {
     StackTraceElement[] stackTraceELement = Thread.currentThread().getStackTrace();
    for (StackTraceElement element : stackTraceELement)
    {
       System.out.println(element.getMethodName());
    }
  }
}
public class ExceptionPrzyklad
{
  public static void main(String[] args)
  {
    StackTraceElement[] stackTraceELement = Thread.currentThread().getStackTrace();
    for (StackTraceElement element : stackTraceELement)
    {
       System.out.println(element.getMethodName());
    }

    method1();
  }

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

  public static void method2()
  {
    method3();
  }

  public static void method3()
  {
    
  }
}

Solution

  • StackTrace Definition:

    A stack trace is a report of the active stack frames at a "specific point in time during the execution of a program". It's also known as a "stack backtrace" or "stack traceback".

    So since it does TraceBack,it holds info about all the locations traced up to the Destination i.e where you've called ".getStackTrace()" function,

    in the first Scenario Above it was called in method3 so it'll contain Trace of all Locations(Source:main) up to method3

    in Second Scenario above where it's called in Main function only prints the Trace of main function

    I Shared info as of my knowledge and would be great if someone notify me where If i'm wrong.