您当前的位置: 首页 >  Java

qq_34412985

暂无认证

  • 0浏览

    0关注

    1061博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java如何将Exception.printStackTrace()转换为String输出

qq_34412985 发布时间:2019-12-09 16:18:33 ,浏览量:0

  1. package com.test1;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.io.StringWriter;  
  5.   
  6. public class T010 {  
  7.   
  8.     /** 
  9.      * @param args 
  10.      */  
  11.     public static void main(String[] args) {  
  12.         try {  
  13.             String[] arr = {"111", "222"};  
  14.             arr[2] = "fff";  
  15.         } catch (Exception e) {  
  16.             String info = getErrorInfoFromException(e);  
  17.             System.out.println(info);  
  18.         }  
  19.     }  
  20.       
  21.     public static String getErrorInfoFromException(Exception e) {  
  22.         try {  
  23.             StringWriter sw = new StringWriter();  
  24.             PrintWriter pw = new PrintWriter(sw);  
  25.             e.printStackTrace(pw);  
  26.             return "\r\n" + sw.toString() + "\r\n";  
  27.         } catch (Exception e1) {  
  28.             return "bad getErrorInfoFromException";  
  29.         }  
  30.     }  
  31. }  
  32.   
  33. 控制台上输出的消息如下所示:  
  34. java.lang.ArrayIndexOutOfBoundsException: 2  
  35.     at com.test1.T010.main(T010.java:14)  
关注
打赏
1653291990
查看更多评论
立即登录/注册

微信扫码登录

3.4084s