Java Throwable to String getStackTrace(Throwable ex)

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

Description

Get exception stack trace.

License

Apache License

Declaration

public static String getStackTrace(Throwable ex) 

Method Source Code

//package com.java2s;
/*//from  ww w.java2  s.  c o  m
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */

import java.io.InputStream;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class Main {
    /**
     * Get exception stack trace.
     */
    public static String getStackTrace(Throwable ex) {
        String result = "";
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.close();
            sw.close();
            result = sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * No exception <code>InputStream</code> close method.
     */
    public static InputStream close(InputStream is) {
        if (is != null) {
            try {
                is.close();
                is = null;
                // System.err.println("close InputStream");
            } catch (Exception ex) {
            }
        }
        return is;
    }

    /**
     * No exception <code>OutputStream</code> close method.
     */
    public static OutputStream close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
                os = null;
                // System.err.println("close OutputStream");
            } catch (Exception ex) {
            }
        }
        return os;
    }

    /**
     * No exception <code>java.io.Reader</code> close method.
     */
    public static void close(Reader rd) {
        if (rd != null) {
            try {
                rd.close();
            } catch (Exception ex) {
            }
        }
    }

    /**
     * No exception <code>java.io.Writer</code> close method.
     */
    public static void close(Writer wr) {
        if (wr != null) {
            try {
                wr.close();
            } catch (Exception ex) {
            }
        }
    }
}

Related

  1. getStackTrace(Throwable aThrowable)
  2. getStackTrace(Throwable aThrowable)
  3. getStackTrace(Throwable e)
  4. getStackTrace(Throwable e)
  5. getStackTrace(Throwable e)
  6. getStackTrace(Throwable ex)
  7. getStackTrace(Throwable ex)
  8. getStackTrace(Throwable exc)
  9. getStackTrace(Throwable exception)