public static void main(String[] args) {
try {
throw new Exception("Exception Test!");
} catch (Exception ex) {
System.out.println("--- getMessage ---");
System.out.println(ex.getMessage());
System.out.println();
System.out.println("--- toString ---");
System.out.println(ex.toString());
System.out.println();
System.out.println("--- printStackTrace ---");
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
ex.printStackTrace(printWriter);
System.out.println(stringWriter.toString());
System.out.println();
System.out.println("--- printStackTrace DIY ---");
System.out.println(ex.getClass().getName() + ": " + ex.getMessage());
StringBuilder sbException = new StringBuilder();
for (StackTraceElement ele : ex.getStackTrace()) {
sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));;
}
System.out.println(sbException);
StackTraceElement stackTraceElement= ex.getStackTrace()[0];
System.err.println("File="+stackTraceElement.getFileName());
System.err.println("Method="+stackTraceElement.getMethodName());
System.err.println("Line="+stackTraceElement.getLineNumber());
}
}