We have analyzed the function usage of Java exception stack through example code and compiled two methods for Java to obtain exception stack information below. The following is all content:
(stack trace) Exception stack trace refers to:
When throwing Throwable, the Throwable object throws multiple method calling layers (method call stack) that the process (shuttle) goes through. The closer you get to the throw statement, the method first enters the exception stack.
(Throwable Causal Chain) Exception Cause Chain:
The cause property in the Throwable class represents the original exception wrapped by the current exception. (Can be called the cause of exception)
When printing the exception stack track, the exception stack of the original exception is recursively printed.
Now let’s analyze the Throwable.printStackTrace() method.
Inside Throwable.printStackTrace(PrintStreamOrWriter s), we can see:
When printing the exception stack, the exception stack of the current exception object this is first printed.
Then print the chain of causes of the exception. (Recursively prints the exception stack of the original exception)
synchronized (s.lock()) { // Print our stack trace// 1. First print the exception stack of the current exception object this. s.println(this); StackTraceElement[] trace = getOurStackTrace(); for (StackTraceElement traceElement : trace) s.println("/tat " + traceElement); // Print suppressed exceptions, if any for (Throwable se : getSuppressed()) se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "/t", dejaVu); // Print cause, if any// 2. Print cause ourCause = getCause(); if (ourCause != null) ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); }Java obtains exception stack information
Method 1:
public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { t.printStackTrace(pw); return sw.toString(); } finally { pw.close(); }}Method 2:
org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);