Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch block in Java - execution statements in catch code

I have a question about the order of the execution of statements in a catch block in Java. when I run the following class Test1 (see below), I expect to have as output first Hi!, then the result of the e.printStackTrace(); statement, and then Bye!. However, I never get this order. Please, look at the outputs, which I have pasted 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.) The more important question: Why I always have Hi! and Bye! printed always one after the other, even though mye.printStackTrace() in the code is between them?

2.) Why sometimes I have the output of the statement e.printStackTrace() 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.

Thank you.

I am using Java 6, and Eclipse (Ganymed).

like image 782
user42155 Avatar asked Feb 04 '09 18:02

user42155


People also ask

Is code executed after try-catch?

Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.

How do you enter a code on try-catch block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Can we use try-catch in catch block?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.


2 Answers

You print "Hi!" and "Bye!" to System.out (i.e. stdout), while the stack trace is printed to System.err (i.e. stderr). The order in which they are printed is determined by when the two buffers are flushed.

like image 42
David Hanak Avatar answered Oct 06 '22 03:10

David Hanak


Exception.printStackTrace() prints to System.err whereas "Hi!" and "Bye!" are on System.out. If you run your program on a regular console, they eventually end up on the screen, but the order may be out. If you are running the program through an IDE (e.g. NetBeans), the streams will probably be color-coded so you can easily distinguish them.

like image 126
Zach Scrivena Avatar answered Oct 06 '22 04:10

Zach Scrivena