Test class
public class Testprintstacktrace {public static void main (string[] args) {
try {
f ();
catch (Exception e) {
E.printstacktrace ();
}
}
public static void F () throws Exception {
throw new Exception ("out of the question.") ");
}
}
View E.printstacktrace (); Source code
public class Throwable implements serializable{
Because System.err is a printstream type, the public void Printstacktrace (PrintStream s) function is invoked
public void Printstacktrace () {
Printstacktrace (System.err);
}
The s=system.err here constructs the Wrappedprintstream (s) and goes directly to the private void Printstacktrace (Printstreamorwriter s).
public void Printstacktrace (PrintStream s) {
Printstacktrace (new Wrappedprintstream (s));
}
Here is the e.printstacktrace () implementation of the underlying code, some do not understand nothing, grasp the skeleton code to see how he throws an exception
private void Printstacktrace (Printstreamorwriter s) {
Guard against malicious overrides of Throwable.equals by
Using a Set with identity equality semantics.
Set<throwable> Dejavu = Collections.newsetfrommap (New identityhashmap<throwable, Boolean> ());
Dejavu.add (this);
Synchronized (S.lock ()) {
Print our stack trace
S.println (this); Here is the new Exception in the Mian method ("out of the question.") "), so the default call to the ToString method here
/*public String toString () {
String s = getclass (). GetName ();
String message = Getlocalizedmessage ();
return (message!= null)? (S + ":" + message): s;
}*/
s= file name in ToString method, message= out the problem.
Shaped like:
This is where each error location is output with a for loop, Getourstacktrace () gets each error location copied to trace, and then with an enhanced for traversal, this is the whole process
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
Throwable ourcause = Getcause ();
if (ourcause!= null)
Ourcause.printenclosedstacktrace (S, Trace, Cause_caption, "", Dejavu);
}
}
Wrappedprintstream class
private static class Wrappedprintstream extends Printstreamorwriter {
Private final PrintStream PrintStream;
The Printstream=system.err here
Wrappedprintstream (PrintStream printstream) {
This.printstream = PrintStream;
}
Object Lock () {
return printstream;
}
void println (Object o) {
Printstream.println (o);
}
}
}