Dump Stack - Musings

By: Nicholas Duchon


System.out.println("Printing stack trace:");
Thread.dumpStack (); // one liner
// more control about displays:
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
  StackTraceElement s = elements[i];
  System.out.println("\tat " + s.getClassName() + "." + s.getMethodName()
          + "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
} // end for

Or you can do the following in response to an exception your code catches in a try/catch block:

      catch (Exception e)
      {
         System.out.println ("We have an error message on line 92 of SeaPortProgram.java\n" + e);
         System.out.println(e.getMessage()); // this results in the "null" output, not exactly informative
         e.printStackTrace(System.out);
      }

Which results in something like the following:
We have an error message on line 92 of SeaPortProgram.java
java.lang.NullPointerException
null
java.lang.NullPointerException
    at World.assignShip(World.java:71)
    at SeaPortProgram.readFile(SeaPortProgram.java:81)
    at SeaPortProgram.<init>(SeaPortProgram.java:47)
    at SeaPortProgram.main(SeaPortProgram.java:171)


ND.