例外内容を文字列で取得します。
例外内容をメール本文等に出力する際に利用します。
/**
* 例外内容取得処理
* @param 例外オブジェクト
* @return 例外内容文字列
*/
public static String getTrace(Throwable th) {
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
if (th != null) {
sb.append(th.getClass().getName() + ":" + th.getMessage());
StackTraceElement[] stack = th.getStackTrace();
if (stack != null) {
for (int i = 0; i < stack.length; i++) {
sb.append(lineSeparator);
sb.append("\tat " + stack[i].toString());
}
}
sb.append(lineSeparator);
Throwable causeTh = th.getCause();
String caused = getCaused(causeTh);
sb.append(caused);
}
return sb.toString();
}
/**
* 例外内容取得処理(原因)
* @param 例外オブジェクト
* @return 例外内容文字列
*/
public static String getCaused(Throwable th) {
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
Throwable chainTh = null;
if (th != null) {
sb.append("Caused by: " + th.getClass().getName() + ":" + th.getMessage());
StackTraceElement[] stack = th.getStackTrace();
if (stack != null) {
for (int i = 0; i < stack.length; i++) {
sb.append(lineSeparator);
sb.append("\tat " + stack[i].toString());
}
}
sb.append(lineSeparator);
chainTh = th.getCause();
} else {
return sb.toString();
}
return sb.append(getCaused(chainTh)).toString();
}
/**
* テストドライバ
* @param args
*/
public static void main(String[] args) {
try {
test();
} catch (Throwable th) {
System.out.println("JavaAPIで例外出力");
th.printStackTrace();
System.out.println();
System.out.println("独自APIで例外出力");
System.out.println(getTrace(th));
}
}
public static void test() throws Exception {
try {
try {
int i = 0;
int j = 100;
int k = j/i; // ここでエラー発生
} catch (Exception e) {
throw new Exception("エラー", e);
}
} catch (Exception e) {
//throw e;
throw new Exception("エラー2", e);
}
}