Here is my simple test code:
class Scratch {
public static void main(String[] args) {
try {
System.out.println("Line 1");
throw new RuntimeException();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
System.out.println("Line 2");
}
}
}
After running I'll get this:
Line 1
Line 2
java.lang.RuntimeException
at Scratch.main(scratch_4.java:5)
Process finished with exit code 0
I thought that "finally" code must be executed at last, but it's not. What is the reason?
CodePudding user response:
By default, printStackTrace
prints to System.err
, whereas you're writing to System.out
. So you're writing to two different streams, and in your particular case it looks like the buffering involved has switched the output order from the actual execution order.
If you either write to a single stream (e.g. using System.err.println
or calling e.printStackTrace(System.out)
) or change your catch
block to just write to System.out
like your other lines do, you'll see the order of try => catch => finally.