Java如何将Exception的堆栈信息转换成String呢?

戚薇 Java经验 发布时间:2023-06-24 15:38:27 阅读数:16604 1
下文笔者讲述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");
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16875923476882.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者