Java Exception StackTrace as String

The following is a Java code to get the Exception Stack trace as String.

public String getStackTraceAsString(Exception e)
{
    if (e == null)
    {
        return "";
    }

    try
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter((Writer) (sw));
        e.printStackTrace(pw);
        pw.flush();
        String exceptionMsg = sw.toString();
        pw.close();
        sw.close();
        return (exceptionMsg);
    }
    catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }

    return "";
}

Search