一. java中e.getMessage()和e.toString() 以及e.printStackTrace()比较
e.getMessage()
只获取异常信息的字符串(不含异常类型)
e.toString()
获取异常类型和异常详细信息
e.printStackTrace()
打印出异常类型和异常详细信息,并且显示异常在后台代码中出现的位置。
案例:
public class ExceptionTest {
public static void main(String[] args) {
try {
System.out.println(1/0);
} catch (Exception e) {
System.out.println("e.getMessage():"+e.getMessage());
System.out.println("————————————————————");
System.out.println("e.toString():"+e.toString());
System.out.println("————————————————————");
e.printStackTrace();
}
}
}
空值台打印结果:
除以零
————————————————————
java.lang.ArithmeticException: 除以零
————————————————————
java.lang.ArithmeticException: 除以零
at com.eric.test.ExceptionTest.main(ExceptionTest.java:7)
二. PrintStackTraceUtil
有些时候,我们在后台catch捕获异常后,希望能将异常具体的报错信息和位置存入数据库中,便于后期跟踪并解决问题,此时我们可以将e.printStackTrace()输出的信息转换成字符串,再将字符串保存到数据库中,以下是将e.printStackTrace()输出信息转换成String字符串的工具类
public class PrintStackTraceUtil {
/**
* 获取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);
e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
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();
}
}
}
}