Java try-catch block - execution instructions in catch code

I have a question about the execution order of statements in a catch block in Java. when I run the next Test1 class (see below), I expect that Hi! will be the output first, then the result is e.printStackTrace (); expression and then bye !. However, I never receive this order. Please look at the outputs I inserted below.

public class Test1 { public static void calculate() { try { int h = 5/0; } catch (ArithmeticException e) { System.out.println("Hi!"); e.printStackTrace(); } System.out.println("Bye!"); } public static void main(String[] args) { calculate(); } } 

Output1:

  Hi!
 Bye!
 java.lang.ArithmeticException: / by zero
     at Test1.calculate (Test1.java:6)
     at Test1.main (Test1.java:15)

Output2:

  java.lang.ArithmeticException: / by zero
     at Test1.calculate (Test1.java:6)
     at Test1.main (Test1.java:15)
 Hi!
 Bye!

I have two questions:

1.) A more important question: why do I always have Hello! and bye! always printed one after another, although mye.printStackTrace () is in the code between them?

2.) Why sometimes I get the output of the e.printStackTrace () instruction before Hi !, and sometimes after Bye !? I have run the program many times, and I cannot understand under what circumstances I get one or the other print.

Thanks.

I am using Java 6 and Eclipse (Ganymed).

+5
java order catch-block
source share
5 answers

Exception.printStackTrace() prints before System.err , while " Hi! " And " Bye! " On System.out . If you run your program on a regular console, they will end up on the screen, but there may be no order. If you run the program through an IDE (such as NetBeans ), the streams are likely to be color coded so you can easily distinguish them.

+18
source share

You type "Hello!". and "Bye!" until System.out (i.e. stdout), while the stack trace is printed on System.err (i.e. stderr). The order in which they are printed is determined by how the two buffers are flushed.

+7
source share

It could be a time issue. Println writes a standard version, while printStackTrace can connect to a standard error. Then it is just a matter of which buffer is first flushed.

+2
source share

A1 - e.printStackTrace () prints to System.err, not System.out, so there are different threads, different print orders. A.

+1
source share

try adding System.out.flush () after each print (including printStackTrace).

0
source share

All Articles