您的位置:首页 > 编程语言 > Java开发

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

2012-01-13 15:03 751 查看
原文地址:/article/4183826.html

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: