码迷,mamicode.com
首页 > 编程语言 > 详细

Java如何将Exception.printStackTrace()转换为String输出

时间:2015-06-16 16:03:56      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

package com.test1;

import java.io.PrintWriter;
import java.io.StringWriter;

public class T010 {

/**
* @param args
*/
public static void main(String[] args) {
try {
String[] arr = {"111", "222"};
arr[2] = "fff";
} catch (Exception e) {
String info = getErrorInfoFromException(e);
System.out.println(info);
}
}

public static String getErrorInfoFromException(Exception e) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return "\r\n" + sw.toString() + "\r\n";
} catch (Exception e2) {
return "bad getErrorInfoFromException";
}
}
}

控制台上输出的消息如下所示:
java.lang.ArrayIndexOutOfBoundsException: 2
at com.test1.T010.main(T010.java:14)

Java如何将Exception.printStackTrace()转换为String输出

标签:

原文地址:http://www.cnblogs.com/zhangzhifeng/p/4580613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!