Java Throwable to String getStackTrace(Throwable t)

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

Description

Get an error's stack trace as a string.

License

Open Source License

Declaration

public static String getStackTrace(Throwable t) 

Method Source Code


//package com.java2s;
/*/*from   ww  w.jav a  2  s.  c o m*/
Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com)
    
This file is part of the Semantic Discovery Toolkit.
    
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
    
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.io.*;

public class Main {
    /**
     * Get an error's stack trace as a string.
     */
    public static String getStackTrace(Throwable t) {
        String result = null;

        try {
            final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            final PrintStream out = new PrintStream(bytesOut);
            t.printStackTrace(out);
            out.close();
            bytesOut.close();
            result = new String(bytesOut.toString("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            result = "StackTrace for '" + t.toString() + "' unavailable due to '" + e.toString() + "'";
        } catch (IOException e) {
            result = "StackTrace for '" + t.toString() + "' unavailable due to '" + e.toString() + "'";
        }

        return result;
    }
}

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)