zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    增加正则项Regularization to Prevent Overfitting
    feature_column、fc.input_layer以及各种类型的column如何转化
    input_fn如何读取数据
    matplotlib.pyplot如何绘制多张子图
    机器学习之杂乱笔记
    Adobe Flash Player
    LSTM/GRU-讲得非常细致
    anaconda python36 tensorflow virtualenv
    畅通工程-HZNU寒假集训
    食物链-HZUN寒假集训
  • 原文地址:https://www.cnblogs.com/heyang78/p/11774925.html
Copyright © 2011-2022 走看看