Home > Software engineering >  JAVA: Different console output in normal and debugging modes using try-catch
JAVA: Different console output in normal and debugging modes using try-catch

Time:04-08

I'm a novice in Java, trying to understand behaviour of JVM. Well, I have a simple code:

public class MyClass {
    public static void main(String[] args) {
        System.out.println(anotherMethod(5));
        System.out.println(anotherMethod(0));
    }

    private static Integer anotherMethod(int x) {
        try {
            return 10 / x;
        }
        catch (ArithmeticException e) {
            e.printStackTrace();
            return 0;
        }
    }
}

In normal mode it returns in console:

2
0
java.lang.ArithmeticException: / by zero
    at MyClass.anotherMethod(MyClass.java:9)
    at MyClass.main(MyClass.java:4)

But when I place breakpoint in line "System.out.println(anotherMethod(5));" and then complete the program via step-by-step execution (F8 in Idea) in debugging mode it returns (and I think this is more correctly):

2
java.lang.ArithmeticException: / by zero
    at MyClass.anotherMethod(MyClass.java:9)
    at MyClass.main(MyClass.java:4)
0

Please, would you be able to explain why the output differs between each other? From my perspective it should be the same and correspond to the second output mentioned in my question.

Thank you so much in advance!

CodePudding user response:

What you are seeing is due to the fact that your code is outputting to two different output streams, stdout and stderr. Due to buffering, it is hard to know just when the system will decide to actually output what is written to these streams in terms of the order of what is output.

The easiest way to solve this problem is to have all of your output go to a single stream. The printStackTrace() method takes an optional output stream argument, which lets you specify that you want the stack trace output to go to stdout instead of stderr. If you do this, you will always get the output in the order you expect:

public static void main(String[] args) {
    System.out.println(anotherMethod(5));
    System.out.println(anotherMethod(0));
}

private static Integer anotherMethod(int x) {
    try {
        return 10 / x;
    }
    catch (ArithmeticException e) {
        e.printStackTrace(System.out);
        return 0;
    }
}

Result:

2
java.lang.ArithmeticException: / by zero
    at com.example.demo.Test1.anotherMethod(Test1.java:12)
    at com.example.demo.Test1.main(Test1.java:7)
0

CodePudding user response:

Well, if you choose "Run", actually the correct name is: "Run without Debugging". So, you are running WITHOUT debugging. If you want to check every detail of your code, use Debugging. if you just want to see the result without much detail, hit "Run without Debugging".

  • Related