Different Outputs Between Intellij and Eclipse

Viewed 100

I have created a code that would help me observe how exception handling works. I typed it all through Intellij IDEA, but it is not outputting in the way I wanted it to. The code looks like this:

public class JVMException {
public static void main(String[] args){
    try{
        faultyMethod();
    } catch (OutOfMemoryError e){
        //prints 1st
        e.printStackTrace();
        fixMemoryLeak();
    }
}

public static void faultyMethod(){
    throw new OutOfMemoryError("JVM is out of memory! Fix memory leak!");
}

public static void fixMemoryLeak(){
    //prints 2nd
    System.out.println("Fixing memory leak...");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        // prints 3rd
        System.out.println("Done! The memory leak is fixed!");
    }
}}

The output should print in the ordered that they were labeled, but I get this result instead:

ConsoleOutput

When I run the same code in either Eclipse or browser IDEs like Repl.it, it prints out in the correct order. Is there some configuration in Intellij that I have to modify in order to get the correct output?

1 Answers

The app runs via Gradle in IntelliJ IDEA and stderr/stdout are not synchronized (probably a limitation of Gradle output logging in the IDE console).

The workaround would be to run the app directly using IDE (without Gradle) by setting the "Build and run using:" option to IntelliJ IDEA:

IntelliJ IDEA

In addition to that IntelliJ IDEA 2019.3+ versions have a setting to sync stderr and stdout streams that you can use with Application run configuration:

Since the next 2019.3 EAP stdout and stderr process streams will influence less each other. In particular, streams shouldn't be mixed in middle of the lines anymore. For example, running Test class (from the issue description) won't produce lines like 41 out41 err. Please note that proper ordering between stdout and stderr is still not guaranteed by default, but there is a way to enforce it with run.processes.with.redirectedErrorStream registry key. To enable it, do the following:

  • "Help | Find Action..." on the main menu; find "Registry..." item and open it;
  • Enable run.processes.with.redirectedErrorStream key.

Enabling it will merge stdout and stderr streams of processes spawned by IDE. This will ensure proper ordering of messages from stdout/stderr. For example, with the registry key enabled, running the Test class will produce the expected output.

However, as a price, merging stdout and stderr will make them indistinguishable: error output will be printed as normal text. Use ANSI coloring to highlight error output differently. Please note that the registry key is supported for requested run/debug configurations only. If it is not supported for your run/debug configuration, please submit a request in issue tracker.

Related