java Exception出錯的棧資訊列印到日誌中
阿新 • • 發佈:2019-02-08
try {
....
} catch (Exception e) {
e.printStackTrace();
log.err(e.getMessage());
.....
}
通常我們都會去這樣找到出錯的資訊,而列印的出錯的資訊棧,因為會輸出到std.err中,所以在我們自己定義的日誌檔案中是不能夠找到的,為了解決這個問題,可以通過如下程式碼解決:
public static String errInfo(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
// 將出錯的棧資訊輸出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
e.getMessage(); 只會獲得具體的異常名稱. 比如說NullPoint 空指標,就告訴你說是空指標
e.printStackTrace();會打出詳細異常,異常名稱,出錯位置,便於除錯用..