java获取完整的异常信息堆栈写入到io中
目录
java获取完整的异常信息堆栈写入到io中
在Java开发中,我们经常要处理各种异常,我们一般用e.toString()或e.getMessage()得到异常信息,但是有时候异常堆栈中会存在很多信息。下边代码就是个工具方法,可以直接获取堆栈中的异常信息。
代码如下:
public static String getErrmessage(Throwable t){
StringWriter stringWriter=new StringWriter();
t.printStackTrace(new PrintWriter(stringWriter,true));
return stringWriter.getBuffer().toString();
}
使用方法:
public static void main(String args[]) throws IOException {
try{
int i=1/0;
}
catch (Exception e){
String exception = ExceptionTest.getErrmessage(e);
//可以将该字符串存储到数据库中或者其他用途。
}
结果如下
java.lang.ArithmeticException: / by zero
at com.wisely.ch10.ExceptionTest.main(ExceptionTest.java:26)
代码简洁,不做解释了。点个赞吧,加个关注也可以。