Java Throwable to String stackTraceToString(final Throwable throwable, final boolean expectNull)

Here you can find the source of stackTraceToString(final Throwable throwable, final boolean expectNull)

Description

Returns a stack trace of the Throwable as a String .

License

Open Source License

Parameter

Parameter Description
throwable The throwable for which to create the stack trace.
expectNull True if null should be returned when throwable is null or false to return "" when throwable is null

Return

null if throwable is null and expectNull is true, "" if throwable is null and expectNull is false, otherwise the stack trace for throwable

Declaration

public static String stackTraceToString(final Throwable throwable, final boolean expectNull) 

Method Source Code


//package com.java2s;

import java.io.PrintWriter;
import java.io.StringWriter;

public class Main {
    /**/*w  ww  . ja v  a2s.c  om*/
     * Returns a stack trace of the {@code Throwable} as a {@code String}.
     * 
     * @param throwable
     *          The throwable for which to create the stack trace.
     * @param expectNull
     *          True if null should be returned when {@code throwable} is null or
     *          false to return "" when {@code throwable} is null
     * @return null if {@code throwable} is null and {@code expectNull} is true,
     *         "" if {@code throwable} is null and {@code expectNull} is false,
     *         otherwise the stack trace for {@code throwable}
     */
    public static String stackTraceToString(final Throwable throwable, final boolean expectNull) {
        if (throwable == null) {
            if (expectNull == true) {
                return null;
            }

            return "";
        }

        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        throwable.printStackTrace(printWriter);
        printWriter.close();
        return stringWriter.toString();
    }
}

Related

  1. stackTraceString(final Throwable exception)
  2. stackTraceToCharSequence( final Throwable error)
  3. stackTraceToHTMLString(Throwable t)
  4. stackTraceToString(final Throwable t)
  5. stackTraceToString(final Throwable thr)
  6. stackTraceToString(Throwable cause)
  7. stackTraceToString(Throwable cause)
  8. stackTraceToString(Throwable e)
  9. stackTraceToString(Throwable e)