Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow Control with exception

When I run the following code, there are two result.

 package scjp;

    public class ExceptionTest {

        public static void main(String[] args) {
            ExceptionTest test = new ExceptionTest();
            test.method1();
        }

        public void method1() {
            try {
                System.out.println("Try Block");

                if (!true) {
                    return;
                } else {
                    throw new RuntimeException();
                }
            }finally {
                System.out.println("Finally Block");
            }
        }
    }

One result is

Try Block
Exception in thread "main" java.lang.RuntimeException
    at scjp.ExceptionTest.method1(ExceptionTest.java:17)
    at scjp.ExceptionTest.main(ExceptionTest.java:7)
Finally Block

and the other,

Try Block
Finally Block
Exception in thread "main" java.lang.RuntimeException
    at scjp.ExceptionTest.method1(ExceptionTest.java:17)
    at scjp.ExceptionTest.main(ExceptionTest.java:7)

Each time I am running the above code, the answer is changing. In my understanding, it should always be same result. Can you help me something???

like image 850
swemon Avatar asked Jan 30 '26 19:01

swemon


1 Answers

The system error output stream (the stack trace above, likely in red in your console) is different than the system output stream (your System.out.println() statements). Hence error messages can be out of sync with normal console output since both streams write to the console, but independently of each other. The differences are as follows:

System.out.println("Some text");

prints to the out stream

System.err.println("Error occurred!");

prints to the error stream

The two can get intermixed when outputting to the same console.

like image 162
Chris Knight Avatar answered Feb 01 '26 13:02

Chris Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!