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).
java order catch-block
user42155
source share