[Java]借助PrintWriter类和StringWriter类,取出异常堆栈信息放入字符串中

在程序开发中,有时我们不仅需要将异常堆栈信息打印在控制台里或是log里,可能还需要将它存在String中,再送到合适的地方,如错误页面,数据库等。

要取异常堆栈信息,具体的函数就是:

    /**
     * Get Exception heap/stack information
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

具体使用可以参看下面代码:

package com.hy.expired;

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

import org.apache.log4j.Logger;

public class StackTrace {
    private static Logger log = Logger.getLogger(StackTrace.class);
    
    public static void main(String[] args) {
        try {
            String[] arr= {"Andy","Bill","Cindy"};
            String fourth=arr[3];
            log.info("fourth="+fourth);
        }catch(Exception e) {
            String stMsg=getStackTrace(e);
            log.info(stMsg);
        }
    }
    
    /**
     * Get Exception heap/stack information
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }
}

执行上面代码,输出内容是:

 INFO [main] - java.lang.ArrayIndexOutOfBoundsException: 3
    at com.hy.expired.StackTrace.main(StackTrace.java:14)

--END-- 2019年11月3日10:00:33

原文地址:https://www.cnblogs.com/heyang78/p/11774925.html