javaexceptionprintstacktrace

Mimic printStackTrace() method in java


My question Is there is any way to implement a method that works like the printStackTrace() I don't know how to start doing this indeed , Is that possible ? Is getStackTrace() is a good choice for me.


Solution

  • Here is the official way how it is done (grepcode format):

    646  private void printStackTrace(PrintStreamOrWriter s) {
    647 // Guard against malicious overrides of Throwable.equals by
    648 // using a Set with identity equality semantics.
    649 Set<Throwable> dejaVu =
    650 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
    651 dejaVu.add(this);
    653 synchronized (s.lock()) {
    654 // Print our stack trace
    655 s.println(this);
    656 StackTraceElement[] trace = getOurStackTrace();
    657 for (StackTraceElement traceElement : trace)
    658 s.println("\tat " + traceElement);
    660 // Print suppressed exceptions, if any
    661 for (Throwable se : getSuppressed())
    662 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
    664 // Print cause, if any
    665 Throwable ourCause = getCause();
    666 if (ourCause != null)
    667 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
    668 }
    669 }

    A bit more concerns are handled than you would anticipate, but you can easily remove any you don't care about.