java 获取e.printStackTrace() 的具体信息,赋值给String 变量
try…catch 大家会经常用,但是e.getMessage() 有时会为null 也有可能满足不了我们的需求 ,此时我们想要e.printStackTrace()的信息,并记录下来
public static void main(String[] args) {
try {
System.out.println(1 / 0);
} catch (Exception e) {
// 进入这个catch中就会打印出我们想要的
System.out.println("结果: e.getMessage()------"+e.getMessage());
System.out.println("结果: e.printStackTrace()--------"+getStackTraceInfo(e));
}
}
/**
* 获取e.printStackTrace() 的具体信息,赋值给String 变量,并返回
*
* @param e
* Exception
* @return e.printStackTrace() 中 的信息
*/
public static String getStackTraceInfo(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
//将出错的栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
} catch (Exception ex) {
return "发生错误";
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
}