Java 将异常堆栈转换为 String


#Java 笔记


用下面的方法可以将异常堆栈转换为String:

public static String getStackInfo(Exception ex) {
    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    return sw.toString();
}

测试示例

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

public class ExceptionTest {

	/**
	 * 自定义异常
	 */
	public static class CustomException extends RuntimeException {
		public CustomException(String msg) {
			super(msg);
		}
	}

	/**
	 * 将异常的堆栈内容转换为 String
	 */
	public static String getStackInfo(Exception ex) {
		StringWriter sw = new StringWriter();
		ex.printStackTrace(new PrintWriter(sw));
		return sw.toString();
	}

	public static void main(String[] args) {
		CustomException ex = new CustomException("异常");
		System.out.println(getStackInfo(ex));
	}

}

执行结果:

ExceptionTest$CustomException: 异常
	at ExceptionTest.main(ExceptionTest.java:25)

参考



( 本文完 )