[Java]借助PrintWriter类和StringWriter类,取出异常堆栈信息放入字符串中
2024-09-03 02:04:23
在程序开发中,有时我们不仅需要将异常堆栈信息打印在控制台里或是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
最新文章
- [No0000AA]Windows 系统环境变量列表
- Oracle 判断某個字段的值是不是数字
- 初学mongodb笔记
- html5基础知识点
- 关于AutoCAD 2014的securityload…
- css3在不同型号手机浏览器上的兼容一览表
- [深入浅出WP8.1(Runtime)]文本框(TextBox)
- LoadTest内存和线程Troubleshooting实战
- 转:Directshow开发的一些例子
- 谈谈JavaScript的2种主要继承方式
- 在Android中让Preference的宽度占满整个屏幕的宽度
- FlyCapture2 fc2Image OpenCV IplImage Conversion 两种图像格式之间的转换
- spring注解注入
- 使用JDBC-ODBC读取Excel文件
- C#中启动外部应用程序
- 在Unicode版Inno Setup中使用ISSkin给安装程序添加皮肤
- 浅谈hbase表中数据导出导入(也就是备份)
- SpringMVC和Struts2的比较
- 基础JAVA程序设计 (多个类方法的实现)
- Divisor Subtraction
热门文章
- NoNodeAvailableException[None of the configured nodes are available:
- U盘装manjaro 18报Python error in job “initcpio”
- 由java派生出来的证书错误
- .NET Core中使用水印
- python3 多线程和多进程
- python中使用uwsgi启动wsgi应用
- 2018/7/31 -zznu-oj -问题 C: 磨刀- 【扩展欧几里得算法的基本应用】
- Lua 学习之基础篇二<;Lua 数据类型以及函数库 汇总>;
- Requests的基础学习
- c语言1博客作业07