在Java中,可以通過以下幾種方式獲取e.printStackTrace()
打印的信息:
e.printStackTrace()
打印異常信息到控制臺(tái):try {
// some code that may throw an exception
} catch (Exception e) {
e.printStackTrace(); // 打印異常信息到控制臺(tái)
}
StringWriter
將異常信息輸出到字符串:try {
// some code that may throw an exception
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String exceptionAsString = sw.toString(); // 將異常信息輸出為字符串
}
ByteArrayOutputStream
將異常信息輸出到字節(jié)數(shù)組:try {
// some code that may throw an exception
} catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
e.printStackTrace(ps);
byte[] exceptionAsBytes = baos.toByteArray(); // 將異常信息輸出為字節(jié)數(shù)組
}
這些方法可以根據(jù)具體的需求選擇適合的方式來獲取異常信息,并根據(jù)需要進(jìn)行處理或記錄。