1. 啥都不做,直接就被抛出来

Java Exception异常信息怎么打印、记录,几种方式自己选_打印

  效果:

Java Exception异常信息怎么打印、记录,几种方式自己选_java_02

 

2.打印栈信息

Java Exception异常信息怎么打印、记录,几种方式自己选_Exception_03

 

3.通过 printStackTrace 的构造方法 直接 转换成字符串 

public static void main(String[] args) throws IOException {
try {
int a=10;
int b=0;
System.out.println(a/b);
} catch (Exception e) {
String exceptionStr = getExceptionStr(e);
System.out.println(exceptionStr);
}
}

核心方法: 

public static String getExceptionStr(Exception e) throws IOException {
//读取异常栈信息
ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(arrayOutputStream));
//通过ByteArray转换输入输出流
BufferedReader fr=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(arrayOutputStream.toByteArray())));
String str;
StringBuilder exceptionStr=new StringBuilder();
while ((str=fr.readLine())!=null){
exceptionStr.append(str);
}
//关闭流
fr.close();
return exceptionStr.toString();
}

 效果:
 

Java Exception异常信息怎么打印、记录,几种方式自己选_打印_04

 

Java Exception异常信息怎么打印、记录,几种方式自己选_java_05