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

  • 相关阅读:
    springboot集成flowable oracle数据库版本报错
    Vue.js中this.$nextTick()的使用
    Centos下虚拟环境的创建以及python3安装
    SaltStack实战
    第一章 Jenkins安装配置
    JavaScript 常用正则表达式
    ps 掉出字符设备面板,修改颜色等
    博客验证码破解
    我终于想起密码了~
    Linux grep 命令
  • 原文地址:https://www.cnblogs.com/heyang78/p/11774925.html
Copyright © 2011-2022 走看看