In my code snippet below, the printStackTrace()
method is called in the catch block
. After running the program you can see that sometimes the printStackTrace()
runs several times in a row instead of running in the order of printStackTrace()
--> catch block
--> finally block
.
If you change the static boolean b
to false
then the System.out.print(e)
executes in order.
So why does the printStackTrace()
behaves in different way? (something with the threads??)
public class PrintStackTrace {
static boolean b = true;
public static void main(String[] args){
for(int i = 0; i < 100; i++){
try{
throw new Exception("[" + i + "]");
}
catch(Exception e){
if(b){
e.printStackTrace();
}
else{
System.out.print(e);
}
System.out.print(" Catch: " + i);
}
finally{
System.out.print(" Finally: " + i);
}
System.out.println();
}
}
}
System.out.flush(); System.err.flush();
lines to your code, the output will be sequential as expected. – Katzen