Java如何将Exception的堆栈信息转换成String呢?
下文笔者讲述Exception堆栈信息转换为String的方法及示例分享,如下所示
堆栈信息转换为String的实现思路
方式1: 使用PrintWriter方法即可将堆栈信息输出 方式2: 自己拼接堆栈信息例:堆栈信息转换为String
方法一:用PrintWriter处理
package com.java265; import java.io.PrintWriter; import java.io.StringWriter; public class GetErrorInfoFromException { public static String getErrorInfoFromException(Exception e) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String s = sw.toString(); sw.close(); pw.close(); return "\r\n" + s + "\r\n"; } catch (Exception ex) { return "获得Exception信息的工具类异常"; } } }
方法二:自己拼接字符串
package com.java265; public class GetExceptionInfo { public static String GetException(Throwable e) { try { String s = e.toString()+"\n"; StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement traceElement : trace) s = s + "\tat " + traceElement + "\n"; for (Throwable se : e.getSuppressed()) s = s + GetException(se); Throwable ourCause = e.getCause(); if (ourCause != null) s = s + GetException(ourCause); s += "\n"; return s; }catch (Exception exception) { exception.printStackTrace(); return "GetExceptionInfo工具异常。"; } } }
测试Demo
package com.java265; public class TestGetException { public static void main(String[] args) { try { new AtestGetException().throwFromBtest(); }catch (Exception e) { System.out.println(GetExceptionInfo.GetException(e)); System.out.println(GetErrorInfoFromException.getErrorInfoFromException(e)); } } } class AtestGetException{ BtestGetException bGetException = new BtestGetException(); public void throwFromBtest() { bGetException.throwException(); } } class BtestGetException{ public void throwException() { Integer.parseInt("a"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。