在程序开发中,有时我们不仅需要将异常堆栈信息打印在控制台里或是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

最新文章

  1. [No0000AA]Windows 系统环境变量列表
  2. Oracle 判断某個字段的值是不是数字
  3. 初学mongodb笔记
  4. html5基础知识点
  5. 关于AutoCAD 2014的securityload…
  6. css3在不同型号手机浏览器上的兼容一览表
  7. [深入浅出WP8.1(Runtime)]文本框(TextBox)
  8. LoadTest内存和线程Troubleshooting实战
  9. 转:Directshow开发的一些例子
  10. 谈谈JavaScript的2种主要继承方式
  11. 在Android中让Preference的宽度占满整个屏幕的宽度
  12. FlyCapture2 fc2Image OpenCV IplImage Conversion 两种图像格式之间的转换
  13. spring注解注入
  14. 使用JDBC-ODBC读取Excel文件
  15. C#中启动外部应用程序
  16. 在Unicode版Inno Setup中使用ISSkin给安装程序添加皮肤
  17. 浅谈hbase表中数据导出导入(也就是备份)
  18. SpringMVC和Struts2的比较
  19. 基础JAVA程序设计 (多个类方法的实现)
  20. Divisor Subtraction

热门文章

  1. NoNodeAvailableException[None of the configured nodes are available:
  2. U盘装manjaro 18报Python error in job “initcpio”
  3. 由java派生出来的证书错误
  4. .NET Core中使用水印
  5. python3 多线程和多进程
  6. python中使用uwsgi启动wsgi应用
  7. 2018/7/31 -zznu-oj -问题 C: 磨刀- 【扩展欧几里得算法的基本应用】
  8. Lua 学习之基础篇二<Lua 数据类型以及函数库 汇总>
  9. Requests的基础学习
  10. c语言1博客作业07