我是靠谱客的博主 魁梧小刺猬,这篇文章主要介绍高效开发之:try catch的异常堆栈信息转字符串处理,现在分享给大家,希望可以做个参考。

在开发场景中,有时会要求异常信息需要记录在案,也就是需要将java Exception异常栈信息进行入库处理。这也就代表不能像以前一样,将catch (Exception e)的异常进行直接e.printStackTrace();

复制代码
1
2
3
4
catch (Exception e){ e.printStackTrace(); }

需要将异常通过 printStackTrace 的构造方转换成字符串,然后再进行入库或者是相关的处理。方法如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static String getExceptionString(Exception e) throws IOException { //读取异常堆栈信息 ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(arrayOutputStream)); //通过字节数组转换输入输出流 BufferedReader fr=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(arrayOutputStream.toByteArray()))); String str; StringBuilder exceptionStr=new StringBuilder(); while ((str=fr.readLine())!=null){ exceptionStr.append(str); } //一定一定要关闭流 fr.close(); return exceptionStr.toString(); }

然后再catch中进行使用即可:

复制代码
1
2
3
4
5
catch (Exception e) { String exceptionStr = getExceptionString(e); System.out.println(exceptionStr);//此处可以进行入库处理等.. }

最后

以上就是魁梧小刺猬最近收集整理的关于高效开发之:try catch的异常堆栈信息转字符串处理的全部内容,更多相关高效开发之:try内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部