美文网首页
java 获取e.printStackTrace() 的具体信息

java 获取e.printStackTrace() 的具体信息

作者: 楼兰King | 来源:发表于2022-10-12 14:25 被阅读0次
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class Test {

    public static void main(String[] args) {
        try {
            System.out.println(1 / 0);
        } catch (Exception e) {
            System.out.println("结果: e.getMessage()------"+e.getMessage());
            System.out.println("结果: e.printStackTrace()--------"+getStackTraceInfo(e));
        }

    }

    /**
     * 获取e.printStackTrace() 的具体信息,赋值给String 变量,并返回
     * 
     * @param e
     *            Exception
     * @return e.printStackTrace() 中 的信息
     */
    public static String getStackTraceInfo(Exception e) {

        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
            pw.flush();
            sw.flush();

            return sw.toString();
        } catch (Exception ex) {

            return "发生错误";
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

    }

}

相关文章

网友评论

      本文标题:java 获取e.printStackTrace() 的具体信息

      本文链接:https://www.haomeiwen.com/subject/neitzrtx.html