Question

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.

Était-ce utile?

La 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.

Autres conseils

If you want to get the stack trace for any moment, you could try this:

Thread.currentThread().getStackTrace();// this return an array of StackTraceElement loop over in order to print them.

or if you just want to get the stack trace in case exception, just use ExceptionUtils from apache common libraries.

ExceptionUtils.getFullStackTrace(ex);

You can do it with the help of Throwable class. See the code below:
The method return the stacktrace.

public String tracePoint()
{
    String trace = "";
    Throwable t = new Throwable();
    StackTraceElement[] s = t.getStackTrace();
    for(int i=0; i<s.length; i++)
    {
        trace += s[i] + "\n";
    }
    return trace;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top