几种方式自己选"/>
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异常信息怎么打印、记录,几种方式自己选
发布评论