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

快来打我* 2022-03-14 11:44 466阅读 0赞

package com.test1;

import java.io.PrintWriter;
import java.io.StringWriter;

public class T010 {

  1. /**
  2. * @param args
  3. */
  4. public static void main(String[] args) {
  5. try {
  6. String[] arr = {"111", "222"};
  7. arr[2] = "fff";
  8. } catch (Exception e) {
  9. String info = getErrorInfoFromException(e);
  10. System.out.println(info);
  11. }
  12. }
  13. public static String getErrorInfoFromException(Exception e) {
  14. try {
  15. StringWriter sw = new StringWriter();
  16. PrintWriter pw = new PrintWriter(sw);
  17. e.printStackTrace(pw);
  18. return "\r\n" + sw.toString() + "\r\n";
  19. } catch (Exception e2) {
  20. return "bad getErrorInfoFromException";
  21. }
  22. }

}

控制台上输出的消息如下所示:
java.lang.ArrayIndexOutOfBoundsException: 2
at com.test1.T010.main(T010.java:14)

发表评论

表情:
评论列表 (有 0 条评论,466人围观)

还没有评论,来说两句吧...

相关阅读