Java Stacktrace to String stackTraceString(Throwable t)

Here you can find the source of stackTraceString(Throwable t)

Description

Return a stack trace as a string.

License

Open Source License

Parameter

Parameter Description
t the Throwable of which the stack trace is desired

Return

a string representation of t's stack trace.

Declaration

public static String stackTraceString(Throwable t) 

Method Source Code

//package com.java2s;
/*/*  www  .j a v  a  2 s.c  o  m*/
 * Copyright 2006 Helsinki Institute for Information Technology
 * 
 * This file is a part of Fuego middleware. Fuego middleware is free software; you can redistribute
 * it and/or modify it under the terms of the MIT license, included as the file MIT-LICENSE in the
 * Fuego middleware source distribution. If you did not receive the MIT license with the
 * distribution, write to the Fuego Core project at fuego-core-users@hoslab.cs.helsinki.fi.
 */

public class Main {
    /**
     * Return a stack trace as a string. Especially when logging it is not convenient to use the
     * {@link Throwable#printStackTrace} methods, since they mess up the logging output. So this
     * method constructs a string similar to what would be printed by
     * {@link Throwable#printStackTrace} and returns that.
     * @param t
     *            the {@link Throwable} of which the stack trace is desired
     * @return a string representation of <code>t</code>'s stack trace.
     */
    public static String stackTraceString(Throwable t) {
        StringBuffer val = new StringBuffer();
        boolean first = true;
        while (t != null) {
            if (first) {
                val.append(t.toString() + "\n");
            } else {
                val.append("Cause: " + t + "\n");
            }
            StackTraceElement[] stackTrace = t.getStackTrace();
            for (int j = 0; j < stackTrace.length; j++) {
                val.append("\tat " + stackTrace[j] + "\n");
            }
            t = t.getCause();
        }
        return val.toString();
    }
}

Related

  1. stacktrace()
  2. stacktrace2string(StackTraceElement[] stackTraceElements)
  3. stackTraceAsString(Exception ex)
  4. stackTraceContains(String... needles)
  5. stackTraceStr(Exception e)
  6. stackTraceToString(Exception e)
  7. stackTraceToString(Exception e, int nBack)
  8. stackTraceToString(Exception ex, String message)
  9. stackTraceToString(Exception exception)