Wednesday, October 04, 2006

Get the messages and/or the stack trace of an exception

While e.printStackTrace(); always writes onto stderr, there are also ways to get the full message of an exception, including all nested exceptions.

public static String getExceptionMessage(Throwable e) {
Throwable cause = e;
String sRet="";
do {
 sRet += "["+cause.getClass().getName() +"] ";
 sRet += cause.getMessage()+"\n";
 cause = cause.getCause();
} while (cause!=null);
return sRet;
}
to get the stack trace is even easier:
public static String getExceptionStackTrace(Throwable e) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(out);
e.printStackTrace(ps);
ps.flush();
return out.toString();
}
In some cases, it is necessary to treat certain exceptions specially. For example, the SQL exception that is raised in case of batch errors contains a special list for the various batch errors. The only way to get these errors is to check the type (of the nested exception), make an explicit cast, and list the batch errors manually.

No comments: