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

效果:

2.打印栈信息

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();
}
效果:
————————————————
版权声明:本文为CSDN博主「小目标青年」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_35387940/article/details/127395977

186

被折叠的 条评论
为什么被折叠?



