Java Throwable to String getStackTrace(Throwable t)

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

Description

Convenience method for getting a stack trace as a string.

License

Apache License

Parameter

Parameter Description
t The throwable to get the stack trace from.

Return

The same content that would normally be rendered via t.printStackTrace()

Declaration

public static String getStackTrace(Throwable t) 

Method Source Code


//package com.java2s;
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *

import java.io.*;

public class Main {
    /**//from   w  w  w.  j a v  a2s.  c om
     * Convenience method for getting a stack trace as a string.
     *
     * @param t The throwable to get the stack trace from.
     * @return The same content that would normally be rendered via <code>t.printStackTrace()</code>
     */
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        pw.flush();
        pw.close();
        return sw.toString();
    }

    /**
     * Calls {@link #toString()} on the specified object if it's not null.
     *
     * @param o The object to convert to a string.
     * @return The object converted to a string, or <jk>null</jk> if the object was null.
     */
    public static String toString(Object o) {
        return (o == null ? null : o.toString());
    }
}

Related

  1. getStackTrace(Throwable t)
  2. getStackTrace(Throwable t)
  3. getStackTrace(Throwable t)
  4. getStackTrace(Throwable t)
  5. getStackTrace(Throwable t)
  6. getStackTrace(Throwable t)
  7. getStackTrace(Throwable t)
  8. getStackTrace(Throwable t)
  9. getStackTrace(Throwable t)