java獲取Exception報錯堆疊資訊,轉換成字串
阿新 • • 發佈:2020-12-30
方法:e.printStackTrace傳入輸出目標引數即可。
package com.lan.test; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; public class ExceptionStack { public static void main(String[] args) { try { System.out.println(Integer.valueOf("17.o")); } catch (Exception e) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); String stackTraceStr = result.toString(); System.out.println(stackTraceStr); } } }
結果: