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

编程入门 行业动态 更新时间:2024-10-09 10:31:40

Java Exception异常信息怎么打印、记录,<a href=https://www.elefans.com/category/jswz/34/1769370.html style=几种方式自己选"/>

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

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();}

 效果:
 

 

 

更多推荐

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

本文发布于:2024-03-07 22:35:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1719089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几种   异常   方式   信息   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!