Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Output different every time? try catch finally exception code

Tags:

java

exception

class TestExceptions {

    public static void main(String[] args) throws Exception {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            throw new RuntimeException();
        } finally {
            System.out.println("finally");
        }
    }
}

Following are the outputs when I try to run the code in eclipse multiple times. I believed so far that whenever the last line of the code from either try/catch block is about to be executed (which could be return or throws new Exception() type of stmt), finally block will be executed, but here the output different every time? Can anyone clarify if my assumption is right or wrong?

try
catch
Exception in thread "main" finally
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)


Exception in thread "main" try
catch
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)
finally
like image 837
Dish Avatar asked Aug 11 '15 08:08

Dish


People also ask

What happens if an exception is thrown from the finally or catch block in Java?

The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.

How do both catch and finally work in an exception program?

Java try, catch and finally blocks helps in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exception by executing alternate application logic or handle the exception gracefully to report back to the user.

What is the difference between try catch and finally?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.

What happens if you exclude catch and use only try and finally?

If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method. The finally block is always executed, whether an exception is thrown or not.


1 Answers

This is clearly because eclipse is printing the error stream and output stream without proper synchronization in console. Lot of people have seen issues because of this.

Execute the program in a command prompt and you will see proper output every time.

like image 159
Codebender Avatar answered Oct 21 '22 19:10

Codebender